Immutable - change elements in array with slice (no splice)

Ingrid Oberbüchler picture Ingrid Oberbüchler · Nov 22, 2016 · Viewed 22.4k times · Source

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

Answer

Mark Williams picture Mark Williams · Nov 22, 2016

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