Last Updated: February 25, 2016
·
3.662K
· wellcaffeinated

splice(0): the fastest way to copy a JS array

Edit: Actually, this modifies the original. Not a true copy. See comments.

No matter what the contents of the array (int, float, string, object, array, mixed), the fastest way to copy the array (by FAR) is:

var copied = original.splice(0);

Here's the JS perf: http://jsperf.com/array-copy-techniques

3 Responses
Add your response

it's more like "move" rather than "copy" :(

over 1 year ago ·

I agree with @zhuangya . This is a volatile copy and should be avoided.

var a = [1, 2, 3],
    b = a.splice(0);
console.log(a); // [] - empty array since all members have been transferred to b
console.log(b); // [1, 2, 3] - transferred members of a
over 1 year ago ·

@twolfson Totally correct. Thanks for the correction.

over 1 year ago ·