Most efficient way to prepend a value to an array

后端 未结 9 1111
予麋鹿
予麋鹿 2020-12-02 04:53

Assuming I have an array that has a size of N (where N > 0), is there a more efficient way of prepending to the array that would not require O(N

9条回答
  •  萌比男神i
    2020-12-02 05:01

    Calling unshift only returns the length of the new array. So, to add an element in the beginning and to return a new array, I did this:

    let newVal = 'someValue';
    let array = ['hello', 'world'];
    [ newVal ].concat(array);
    

    or simply with spread operator:

    [ newVal, ...array ]
    

    This way, the original array remains untouched.

提交回复
热议问题