Immutable Array Element Deletion in JavaScript
Let's now learn how to perform immutable deletion of elements in an array. As an example, let's say we have some array:
let arr = [1, 2, 3, 4, 5];
Let the index for deletion
be stored in the variable ind:
let ind = 3;
Let's delete the element with the specified index. According to our approach, we should make a copy of the array and delete the element from the copy. Let's do this:
let copy = Object.assign([], arr);
copy.splice(ind, 1);
let res = copy;
Let's use the second approach:
let res = [
...arr.slice(0, ind),
...arr.slice(ind + 1)
];
Create a button that, when clicked, will delete an element from the array. Let the index of the element to be deleted be stored in a variable.