I want to achieve the following:
>>> a = [1, 2] [1, 2] >>> b = [3, 4, 5] [3, 4, 5] >>> SOMETHING HERE >>> a [1, 2, 3, 4, 5]
I know there’s a
a.concat(b) method, but it creates a new array instead of simply extending the first one. I’d like an algorithm that works efficiently when
a is significantly larger than
b (i.e. one that does not copy
Note: This is not a duplicate of How to append something to an array? — the goal here is to add the whole contents of one array to the other, and to do it “in place”, i.e. without copying all elements of the extended array.
If your browser does not support ECMAScript 6, you can use
>>> a.push.apply(a, b)
Or perhaps, if you think it’s clearer:
Please note that all these solutions will fail with a stack overflow error if array
b is too long (trouble starts at about 100,000 elements, depending on the browser).
If you cannot guarantee that
b is short enough, you should use a standard loop-based technique described in the other answer.
Answered By – DzinX