Edited on 2016 october
In this code example I use "array.filter(...)" function to remove unwanted items from array, this function doesn't change the original array and creates a new one. If your browser don't support this function (e.g. IE before version 9, or Firefox before version 1.5), consider using the filter polyfill from Mozilla.
ECMAScript 5 code
var value = 3;
var arr = [1, 2, 3, 4, 5, 3];
arr = arr.filter(function(item) {
return item !== value;
});
console.log(arr);
// [ 1, 2, 4, 5 ]
ECMAScript 6 code
let value = 3;
let arr = [1, 2, 3, 4, 5, 3];
arr = arr.filter(item => item !== value);
console.log(arr);
// [ 1, 2, 4, 5 ]
An additional advantage of this method is that you can remove multiple items
['a', 'b', 'c', 'd'].filter((_, i) => i != 2 && i != 3) // makes ['a', 'b']
Whereas the delete
/remove
mutators update the array indexes after every delete/remove and, thus, invalidate the index array of elements that you want to remove.
indexOf
in IE. – Scotty.NET Sep 13 '13 at 7:48delete
should be more performant in the short term, because it won't have to shift the later items.forEach
,map
andfilter
will automatically skip processing for undefined (deleted) items. But it's probably not ideal if you will be adding a lot of things to your array in future, or reading it many times. – joeytwiddle Jul 29 at 8:55