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

后端 未结 6 1886
逝去的感伤
逝去的感伤 2021-01-11 10:44

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         


        
相关标签:
6条回答
  • 2021-01-11 11:07

    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);
    
    0 讨论(0)
  • 2021-01-11 11:09
    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]
    
    0 讨论(0)
  • 2021-01-11 11:23

    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

    0 讨论(0)
  • 2021-01-11 11:23

    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
    
    0 讨论(0)
  • 2021-01-11 11:24

    Arrays are objects, use Object.assign() and access elements with property name expressions.

    var numToMove = 2;
    console.log(Object.assign(list, {[numToMove]: list[numToMove+1]}, 
    {[numToMove+1]: list[numToMove]}));
    // [1, 2, 4, 3, 5]
    
    0 讨论(0)
  • 2021-01-11 11:30

    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)];
    
    0 讨论(0)
提交回复
热议问题