remove item from array without mutating javascript code example
Example 1: javascript remove one element from array
const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1);
}
// array = [2, 9]
console.log(array);
Example 2: Remove list element without mutation
I assume you mean that you want to create a new list without a given element,
instead of changing the original list. One way is to use a list comprehension:
m = ['a', 'b', 'c']
n = [x for x in m if x != 'a']
n is now a copy of m, but without the 'a' element.
Another way would of course be to copy the list first
m = ['a', 'b', 'c']
n = m[:]
n.remove('a')
If removing a value by index, it is even simpler
n = m[:index] + m[index+1:]
Example 3: javascript splice without changing array
var myArray = ["one", "two", "three"];
var cloneArray = myArray.slice();
myArray.splice(1, 1);
console.log(myArray);
console.log(cloneArray);