Most efficient way to prepend a value to an array

后端 未结 9 1128
予麋鹿
予麋鹿 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条回答
  •  悲&欢浪女
    2020-12-02 05:06

    With ES6, you can now use the spread operator to create a new array with your new elements inserted before the original elements.

    // Prepend a single item.
    const a = [1, 2, 3];
    console.log([0, ...a]);

    // Prepend an array.
    const a = [2, 3];
    const b = [0, 1];
    console.log([...b, ...a]);

    Update 2018-08-17: Performance

    I intended this answer to present an alternative syntax that I think is more memorable and concise. It should be noted that according to some benchmarks (see this other answer), this syntax is significantly slower. This is probably not going to matter unless you are doing many of these operations in a loop.

提交回复
热议问题