How to extend an existing JavaScript array with an

2018-12-31 20:58发布

There doesn't seem to be a way to extend an existing JavaScript array with another array, i.e. to emulate Python's extend method.

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 a).

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.

14条回答
公子世无双
2楼-- · 2018-12-31 21:47

The .push method can take multiple arguments, so by using .apply to pass all the elements of the second array as arguments to .push, you can get the result you want:

>>> a.push.apply(a, b)

Or perhaps, if you think it's clearer:

>>> Array.prototype.push.apply(a,b)

If your browser supports ECMAScript 6, you can use the spread operator, which is more compact and elegant:

>>> a.push(...b)

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.

查看更多
十年一品温如言
3楼-- · 2018-12-31 21:48

Another solution to merge more than two arrays

var a = [1, 2],
    b = [3, 4, 5],
    c = [6, 7];

// Merge the contents of multiple arrays together into the first array
var mergeArrays = function() {
 var i, len = arguments.length;
 if (len > 1) {
  for (i = 1; i < len; i++) {
    arguments[0].push.apply(arguments[0], arguments[i]);
  }
 }
};

Then call and print as:

mergeArrays(a, b, c);
console.log(a)

Output will be: Array [1, 2, 3, 4, 5, 6, 7]

查看更多
萌妹纸的霸气范
4楼-- · 2018-12-31 21:49

Update 2018: A better answer is a newer one of mine: a.push(...b). Don't upvote this one anymore, as it never really answered the question, but it was a 2015 hack around first-hit-on-Google :)


For those that simply searched for "JavaScript array extend" and got here, you can very well use Array.concat.

var a = [1, 2, 3];
a = a.concat([5, 4, 3]);

Concat will return a copy the new array, as thread starter didn't want. But you might not care (certainly for most kind of uses this will be fine).


There's also some nice ECMAScript 6 sugar for this in the form of the spread operator:

const a = [1, 2, 3];
const b = [...a, 5, 4, 3];

(It also copies.)

查看更多
回忆,回不去的记忆
5楼-- · 2018-12-31 21:51

The answer is super simple.

>>> a = [1, 2]
[1, 2]
>>> b = [3, 4, 5]
[3, 4, 5]
>>> SOMETHING HERE
(The following code will combine the two arrays.)

a = a.concat(b);

>>> a
[1, 2, 3, 4, 5]

Concat acts very similarly to JavaScript string concatenation. It will return a combination of the parameter you put into the concat function on the end of the array you call the function on. The crux is that you have to assign the returned value to a variable or it gets lost. So for example

a.concat(b);  <--- This does absolutely nothing since it is just returning the combined arrays, but it doesn't do anything with it.
查看更多
还给你的自由
6楼-- · 2018-12-31 21:52

I feel the most elegant these days is:

arr1.push(...arr2);

The MDN article on the spread operator mentions this nice sugary way in ES2015 (ES6):

A better push

Example: push is often used to push an array to the end of an existing array. In ES5 this is often done as:

var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
// Append all items from arr2 onto arr1
Array.prototype.push.apply(arr1, arr2);

In ES6 with spread this becomes:

var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);

Do note that arr2 can't be huge (keep it under about 100 000 items), because the call stack overflows, as per jcdude's answer.

查看更多
临风纵饮
7楼-- · 2018-12-31 21:57

I can see very nice answers, and it all depends on your array size, your requirement and goal. It can be done in different ways.

I suggest using a JavaScript for loop:

var a = [1, 2];
var b = [3, 4, 5];

for (i = 0; i < b.length; i++) {
    a.push(b[i]);
}

console.log(a) output will be

Array [ 1, 2, 3, 4, 5 ]

Then you can make your own function:

function extendArray(a, b){
    for (i = 0; i < b.length; i++) {
        a.push(b[i]);
    }
    return a;
}

console.log(extendArray(a, b)); output will be

Array [ 1, 2, 3, 4, 5 ]
查看更多
登录 后发表回答