Languages
[Edit]
EN

JavaScript - remove element from array by value

0 points
Created by:
trincot
330

In this article, we would like to show you how to remove elements from an array by value in JavaScript.

Quick solution:

const removedElements = array.splice(index, 1);

Note:

The above code removes element with specified index from array returning removed elements - one in our case.

 

Practical example

In this example, we use indexOf() method to get index of the item that we want to remove. Then we use splice() method to remove the element.

// ONLINE-RUNNER:browser;

//    index:    0    1    2    3
const array = ['a', 'b', 'c', 'd'];

const elementToRemove = 'b';
const index = array.indexOf(elementToRemove);

if (index !== -1) {
    const removedElements = array.splice(index, 1);  // removes elementToRemove

    console.log(array);			   // [a,c,d]
    console.log(removedElements);  // ['b']
}

See also

  1. JavaScript - remove specific array item by value or reference

References

  1. Array.prototype.indexOf() - JavaScript | MDN
  2. Array.prototype.splice() - JavaScript | MDN
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join