Ask Question

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]
TypeScriptJavaScriptarray

2187 views

Authorยดs AnkiCodes image

AnkiCodes

๐Ÿ‘€
1
Last edited on

1 Answer available

Best answer

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]