Languages
[Edit]
EN

JavaScript - remove element from array by value

0 points
Created by:
trincot
360

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(removedElements);  // ['b']
}

console.log(array);  // [a,c,d]

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

Alternative titles

  1. JavaScript - delete element from array by value
  2. JavaScript - how to unset element in array (by value)
  3. JavaScript - remove matching element of array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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