JSFiddle - React, Tailwind, and code Playground
by NickU
JavaScript
/*
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"]
console.log('____________');
items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
function E(arr,idx)
{
return arr.filter(function(e) { return e !== 'seven' });
}
items = E(items, 'c');
console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
console.log('____________');
items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
function removeItem(arr, item){
return arr.filter(f => f !== item)
}
items = removeItem(items, 'c');
console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]