Net-informations.com

Remove elements from a JavaScript Array

You can use the arrayObject.filter() method to remove the item(s) from an array at specific index in JavaScript. The syntax for removing array elements can be given with:

The filter() method creates a new array with all the elements that pass the test implemented by the callback() function and it does not change the original array. Internally, the filter() method iterates over each element of the array and pass each element to the callback function. If the callback function returns true, it includes the element in the return array.

examples

Output:

Using ECMAScript 6 code

Output:

Using ECMAScript 7 code

Output:

An additional advantage of above method is that you can remove multiple items from JavaScript array.


remove elements from Javascript array

Removing specific item suing splice()

You can also use the splice() method to remove the item from an array at specific index in JavaScript. This method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. This means that splice() overwrites the original array.

example

Output:

In the above example, find the index of the array element you want to remove using indexOf(), and then remove that index with splice() method. The second parameter of splice() is the number of elements to remove.










net-informations.com (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About