JS: How can I remove a specific item from an array?
I am looking for a short way to remove an item from array
const arr = [1, 2, 3, 4, 5];
// something like
arr.remove(2); // [1, 3, 4, 5]
2187 views
๐
1
I am looking for a short way to remove an item from array
const arr = [1, 2, 3, 4, 5];
// something like
arr.remove(2); // [1, 3, 4, 5]
2187 views
The easiest way is to use the .filter(() => boolean)
function, which returns a new (filtered) array. The passed callback function tests each item in the array and returns true
to keep the item false
otherwise.
In you case:
const arr = [1, 2, 3, 4, 5];
const newArr = arr.filter((value) => value !== 2);
// newArr => [1, 3, 4, 5]