Remove a specific item from an array in JavaScript
Today we’ll show you how to remove a specific item from an array in JavaScript. There are multiple ways to remove an element from an array using JavaScript.
You may check the few more articles related to the array.
Ways to remove a specific item from an array
1. splice() method
Here, In the first method, we will use the splice() method along with the indexOf() method. First, find the index of a specific item using the indexOf()
method that you want to remove from an array. After that we have to remove that index using the splice()
method.
1 2 3 4 5 6 7 8 9 | const arr = [2, 3, 5, 9]; const index = arr.indexOf(3); if (index > -1) { arr.splice(index, 1); } console.log(arr); // Output: [2, 5, 9] |
2. filter() method
Using the filter() method, we can easily remove the items from the list. It’s most preferable method to remove an item.
Example 1
1 2 3 4 | let arr = [2, 3, 5, 9]; arr = arr.filter(x => x !== 3); // Output: [2, 5, 9] |
In the next example, we will see the array that contains the list of the object and remove the specific object from the list using the filter()
method.
Example 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | let arr = [ { userId: 1, id: 1, title: "delectus aut autem", completed: false }, { userId: 2, id: 2, title: "quis ut nam facilis et officia qui", completed: false }, { userId: 1, id: 3, title: "fugiat veniam minus", completed: false } ]; arr = arr.filter(x => x.userId !== 2); /* Output: [ { userId: 1, id: 1, title: "delectus aut autem", completed: false }, { userId: 1, id: 3, title: "fugiat veniam minus", completed: false } ] */ |
That’s it for today.
Thank you for reading. Happy Coding..!!