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).concat(list.slice(removeElement+1)) // [1,2,4,5]
...next push number 3 after number 4 without splice
You can create an immutable copy of an array using Array. slice() with no arguments, or with the Array.
slice, from, map and filter are immutable because it creates a new array without mutating the original array. Object method which are immutable are object. assign.
slice() The slice array method makes a shallow copy of the sliced array and returns the copied array. It does not mutate the original array.
The slice( ) method copies a given part of an array and returns that copied part as a new array. It doesn't change the original array. The splice( ) method changes an array, by adding or removing elements from it. Note: the Slice( ) method can also be used for strings.
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 3
var 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 3
var es6List = [
...list.slice(0, removeElement),
...list.slice(removeElement+1)
];
console.log(es6List);
fiddle
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)];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With