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

后端 未结 6 1887
逝去的感伤
逝去的感伤 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: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]
    

提交回复
热议问题