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

后端 未结 6 1890
逝去的感伤
逝去的感伤 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);
    

提交回复
热议问题