Horje Website
Concatenating Arrays‌ JavaScript

Two Arrays

 
 
  1. var array1 = [1, 2];
  2. var array2 = [3, 4, 5];
  3. Version ≥ 3
  4. var array3 = array1.concat(array2); // returns a new array
  5. Version ≥ 6
  6. var array3 = [...array1, ...array2]

Results in a new Array:

[1, 2, 3, 4, 5]

 

Multiple Arrays

 
 
  1. var array1 = ["a", "b"],
  2. array2 = ["c", "d"],
  3. array3 = ["e", "f"],
  4. array4 = ["g", "h"];

 

Provide more Array arguments to array.concat()

 
 
  1. var arrConc = array1.concat(array2, array3, array4);
  2. Version ≥ 6

 

Provide more arguments to []

 
 
  1. var arrConc = [...array1, ...array2, ...array3, ...array4]

 

Results in a new Array:

 
 
  1. ["a", "b", "c", "d", "e", "f", "g", "h"]

 

Without Copying the First Array

 
 
  1. var longArray = [1, 2, 3, 4, 5, 6, 7, 8],
  2. shortArray = [9, 10];
  3. Version ≥ 3

 

Provide the elements of shortArray as parameters to push using Function.prototype.apply

 
 
  1. longArray.push.apply(longArray, shortArray);
  2. Version ≥ 6

 

Use the spread operator to pass the elements of shortArray as separate arguments to push

 
 
  1. longArray.push(...shortArray)

 

The value of longArray is now:

 
 
  1. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 

Note that if the second array is too long (>100,000 entries), you may get a stack overflow error (because of how

apply works). To be safe, you can iterate instead:

 
 
  1. shortArray.forEach(function (elem) { longArray.push(elem);
  2. });

 

Array and non-array values

 
 
  1. var array = ["a", "b"];
  2. Version ≥ 3
  3. var arrConc = array.concat("c", "d");
  4. Version ≥ 6
  5. var arrConc = [...array, "c", "d"]

 

Results in a new Array:

 
 
  1. ["a", "b", "c", "d"]

 

You can also mix arrays with non-arrays

 
 
  1. var arr1 = ["a","b"];
  2. var arr2 = ["e", "f"];
  3. var arrConc = arr1.concat("c", "d", arr2);

 

Results in a new Array:

 
 
  1. ["a", "b", "c", "d", "e", "f"]

 

Noted that: Above full tutorial makes good

Published:
December 31, 2022
Author:
admin
Category:
Javascript Source Code
Views:
22

This article was posted in Javascript Source Code. Bookmark the permalink. Follow comments with the RSS feed for this post.Post a Comment or leave a trackback: Trackback URL.

Leave a Reply

Your email address will not be published. Required fields are marked *

 

Horje © 2011 - 2023