In JavaScript, you can remove an array element by value in the following ways:
Using Array.prototype.filter()
You can remove array elements by value (in an immutable way) by using Array.prototype.filter()
. It adds all values that return true
(for the test implemented by the provided callback function) to a new array. It has the following syntax:
// ES5+
const filteredArray = array.filter(function (currValue) {
return currValue !== valueToRemove;
});
With ES6 arrow function, you can shorten the syntax, for example, like so:
// ES6+
const filteredArray = array.filter(currValue => currValue !== valueToRemove);
For example:
const array = ['foo', 'bar', 'baz', 'qux', 'foo'];
const filteredArray = array.filter(value => value !== 'foo');
console.log(filteredArray); // ['bar', 'baz', 'qux']
Using Array.prototype.splice()
You can remove array elements by value (in a mutable way) by using Array.prototype.splice()
with Array.prototype.indexOf()
, like so:
let index;
while ((index = array.indexOf(valueToRemove)) !== -1) {
array.splice(index, 1);
};
For example:
const array = ['foo', 'bar', 'baz', 'qux', 'foo'];
let index;
while ((index = array.indexOf('foo')) !== -1) {
array.splice(index, 1);
};
console.log(array); // ['bar', 'baz', 'qux']
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.