What is the difference between using the delete operator on the array element as opposed to using the Array.splice method?
For example:
myArray = [\
I stumbled onto this question while trying to understand how to remove every occurrence of an element from an Array. Here's a comparison of splice
and delete
for removing every 'c'
from the items
Array.
var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
while (items.indexOf('c') !== -1) {
items.splice(items.indexOf('c'), 1);
}
console.log(items); // ["a", "b", "d", "a", "b", "d"]
items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
while (items.indexOf('c') !== -1) {
delete items[items.indexOf('c')];
}
console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]