How to extend an existing JavaScript array with another array, without creating a new array

后端 未结 16 1849
深忆病人
深忆病人 2020-11-22 07:38

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 th

相关标签:
16条回答
  • 2020-11-22 08:01

    First a few words about apply() in JavaScript to help understand why we use it:

    The apply() method calls a function with a given this value, and arguments provided as an array.

    Push expects a list of items to add to the array. The apply() method, however, takes the expected arguments for the function call as an array. This allows us to easily push the elements of one array into another array with the builtin push() method.

    Imagine you have these arrays:

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

    and simply do this:

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

    The result will be:

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

    The same thing can be done in ES6 using the spread operator ("...") like this:

    a.push(...b); //a = [1, 2, 3, 4, 5, 6, 7]; 
    

    Shorter and better but not fully supported in all browsers at the moment.

    Also if you want to move everything from array b to a, emptying b in the process, you can do this:

    while(b.length) {
      a.push(b.shift());
    } 
    

    and the result will be as follows:

    a = [1, 2, 3, 4, 5, 6, 7];
    b = [];
    
    0 讨论(0)
  • 2020-11-22 08:01

    This solution works for me (using the spread operator of ECMAScript 6):

    let array = ['my', 'solution', 'works'];
    let newArray = [];
    let newArray2 = [];
    newArray.push(...array); // Adding to same array
    newArray2.push([...array]); // Adding as child/leaf/sub-array
    console.log(newArray);
    console.log(newArray2);

    0 讨论(0)
  • 2020-11-22 08:01

    Super simple, does not count on spread operators or apply, if that's an issue.

    b.map(x => a.push(x));
    

    After running some performance tests on this, it's terribly slow, but answers the question in regards to not creating a new array. Concat is significantly faster, even jQuery's $.merge() whoops it.

    https://jsperf.com/merge-arrays19b/1

    0 讨论(0)
  • 2020-11-22 08:02

    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.
    
    0 讨论(0)
  • 2020-11-22 08:03

    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.

    0 讨论(0)
  • 2020-11-22 08:05

    You should use a loop-based technique. Other answers on this page that are based on using .apply can fail for large arrays.

    A fairly terse loop-based implementation is:

    Array.prototype.extend = function (other_array) {
        /* You should include a test to check whether other_array really is an array */
        other_array.forEach(function(v) {this.push(v)}, this);
    }
    

    You can then do the following:

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

    DzinX's answer (using push.apply) and other .apply based methods fail when the array that we are appending is large (tests show that for me large is > 150,000 entries approx in Chrome, and > 500,000 entries in Firefox). You can see this error occurring in this jsperf.

    An error occurs because the call stack size is exceeded when 'Function.prototype.apply' is called with a large array as the second argument. (MDN has a note on the dangers of exceeding call stack size using Function.prototype.apply - see the section titled "apply and built-in functions".)

    For a speed comparison with other answers on this page, check out this jsperf (thanks to EaterOfCode). The loop-based implementation is similar in speed to using Array.push.apply, but tends to be a little slower than Array.slice.apply.

    Interestingly, if the array you are appending is sparse, the forEach based method above can take advantage of the sparsity and outperform the .apply based methods; check out this jsperf if you want to test this for yourself.

    By the way, do not be tempted (as I was!) to further shorten the forEach implementation to:

    Array.prototype.extend = function (array) {
        array.forEach(this.push, this);
    }
    

    because this produces garbage results! Why? Because Array.prototype.forEach provides three arguments to the function it calls - these are: (element_value, element_index, source_array). All of these will be pushed onto your first array for every iteration of forEach if you use "forEach(this.push, this)"!

    0 讨论(0)
提交回复
热议问题