Javascript: click the whole list?

Is there a built-in way to add one list to another, for example:

var a = [1,2,3]; a.append([4,5]); // now a is [1,2,3,4,5]; 

concat() does something similar, but returns a result. I want something that modifies an existing list, like push()

+6
javascript
source share
5 answers

push will work, but you also need to use apply .

 var a = [1,2,3]; a.push.apply(a, [4,5]) 
+16
source share
 var list = [1, 2]; 

People have already shown you how to do this:

  • push: list.push.apply(list, [3, 4]);
  • concat: list = list.concat([4, 5]);

But I want to talk about the ES6 distribution operator : list.push(...[3, 4]); .

Keep in mind that not many browsers are currently supported (you can use transpilers).

+5
source share

If you are using ES6, you can use the spread operator

eg: -

 listOne = [1,2,3] listTwo = [4,5,6] listTwo.push(...listOne) 
+4
source share

How about this:

 var a = [1, 2, 3]; a = a.concat([4, 5]); // a is now [1, 2, 3, 4, 5] 
+3
source share

Since I just wrote a web application in which many arrays should be combined and where performance is critical, I tested which method is faster in this jsperf . The results are quite interesting.

In my test, I add 10 items to a list or an array of 10,000 items.

Here are test cases, from the fastest to the slowest. Results are measured in Chrome 62, but Firefox 47 works similarly:

  • LinkedList.prototype.concat : 90,313,485 ops / sec

     list.concat(concatList); // This function has to change only 1-2 refences 
  • Array.prototype.push in for loop : 3,794,962 ops / sec

     for (var i = 0, len = concatArr.length; i < len; i++) { array.push(concatArr[i]); } // Probably fastest in real life 
  • Array.prototype.push.apply : 2,193,469 ops / sec

     array.push.apply(array, concatArr); 
  • Array.prototype.concat : Array.prototype.concat ops / sec

     array = array.concat(concatArr); 

Unfortunately, the LinkedList version does not work if you want to combine an array / list into multiple LinkedList s. It also has no advantage if the array must be copied before LinkedList before each concat operation. So, for me, the winner is for the cycle .

One reason not to use Array.prototype.push.apply is because it fails if the concatenated array is too large. According to this answer , a concatenated array cannot have more than 500,000 elements in Firefox and 150,000 elements in Chrome.

I excluded the statement because it is not supported by all browsers. In Chrome it is about as fast as Array.prototype.push.apply , in Firefox it is a bit slower.

0
source share

All Articles