How to remove array element in JavaScript?

javascript array arrays

Removing array element is done with splice method, same as for inserting elements. To remove element, we need to know it's index - the position at which it is placed in array. Index starts from zero, and subsequent elements are integer numbers. We can obtain index by value using indexOf method.

Getting Element Index

var x = [111, 222, 333];
var idx = x.indexOf(222);
// idx is now 1

Please note, that when having several same values indexOf will return first index found. If element is not found, the indexOf method will return -1.

Removing Element with Splice

Splice takes index as a first argument and number of elements as a second one. The index argument will indicates the index at which operation (in this case removing) will begin. The second argument - number of elements - indicates how many elements to remove. In summary, to remove second element, we need to call splice with index of one - as indexes are started at zero - and number of elements being one too.

var x = [111, 222, 333];
var idx = x.indexOf(222); // returns 1
x.splice(idx, 1); // return [222]
// x is now [111,333]

The method returns array of removed elements. In our example we discard result.