Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).concat(list.slice(removeElement+1)) // [1,2,4,5]

...next push number 3 after number 4 without splice

like image 589
Ingrid Oberbüchler Avatar asked Nov 22 '16 08:11

Ingrid Oberbüchler


People also ask

Is array slice immutable?

You can create an immutable copy of an array using Array. slice() with no arguments, or with the Array.

Is slice mutable or immutable?

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.

Does slice mutate the array?

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.

Does slice modify 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.


2 Answers

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

like image 181
Mark Williams Avatar answered Oct 16 '22 05:10

Mark Williams


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)];
like image 39
ide Avatar answered Oct 16 '22 06:10

ide