Immutable - Change Elements In Array With Slice (no Splice)
How is possible to change 3/4 elements? Expected output is [1,2,4,3,5] let list = [1,2,3,4,5]; const removeElement = list.indexOf(3); // remove number 3 list.slice(0, removeElement
Solution 1:
slice doesn't mutate the array on which it operates so you need to assign a value to what it returns
let list = [1,2,3,4,5];
const removeElement = list.indexOf(3); // remove number 3var newList = list.slice(0, removeElement).concat(list.slice(removeElement+1)) // [1,2,4,5]
If you are prepared to use ES2015 syntax, you can use the spread operator as follows:
const removeElement = list.indexOf(3); // remove number 3var es6List = [
...list.slice(0, removeElement),
...list.slice(removeElement+1)
];
console.log(es6List);
Solution 2:
The simplest way to write this is to use the spread operator:
let newList = [...list.slice(0, 2), list[4], list[3], ...list.slice(4)];
Solution 3:
var list = [1,2,3,4,5];
var numToRemove = 3;
var removeElementIndex = list.indexOf(numToRemove);
var afterRemoveElement = list[removeElementIndex+1];
list.slice(0, removeElementIndex).concat(afterRemoveElement).concat(numToRemove).concat(list.slice(removeElementIndex+2)) // [1,2,4,3,5]
Solution 4:
Object.assign actually works here
const newList = Object.assign([], list, {
2: list[3],
3: list[2],
});
list // [1,2,3,4,5]
newList // [1,2,4,3,5]
newList === list // false
Solution 5:
The easer solution might be using filter
instead of splice or slice. According to documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
It means the original array stays immutable. The only difference is that in this case, you have to know the value you want to delete instead of index.
let list = [1,2,3,4,5];
list.filter((item) => item !== 3);
Post a Comment for "Immutable - Change Elements In Array With Slice (no Splice)"