javascript tutorial - [Solved-5 Solutions] Remove a Particular Element - javascript - java script - javascript array
Problem:
How to remove a particular element from an array in javascript ?
Solution 1:
First, find the index of the element you want to remove:
Then remove it with splice:
The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.
If we need indexOf in an unsupported browser, try the following polyfill. Find more info about this polyfill here.
Solution 2:
- we don't know how you are expecting
array.remove(int)
to behave. There are three possibilities we can think of that you might be wanting. - To remove an element of an array at an index i:
- If we want to remove every element with value number from the array:
If we just want to make the element at index i no longer exist, but you don't want the indexes of the other elements to change:
Solution 3:
- Depends on whether you want to keep an empty spot or not.
- If we do want an empty slot, delete is fine:
If we don't, you should use the splice method:
And if you need the value of that item, you can just store the returned array's element:
- In case you want to do it in some order, you can use
array.pop()
for the last one orarray.shift()
for the first one (and both return the value of the item too). - And if you don't know the index of the item, you can use
array.indexOf( item )
to get it (in aif()
to get one item or in awhile()
to get all of them).array.indexOf( item )
returns either the index or -1 if not found.
It loops through the array backwards (since indices and length will change as items are removed) and removes the item if it's found. It works in all browsers.