Skip to content

Instantly share code, notes, and snippets.

@yesvods
Created August 15, 2015 11:13
Show Gist options
  • Save yesvods/51af798dd1e7058625f4 to your computer and use it in GitHub Desktop.
Save yesvods/51af798dd1e7058625f4 to your computer and use it in GitHub Desktop.
Merge Arrays in one with ES6 Array spread
const arr1 = [1,2,3]
const arr2 = [4,5,6]
const arr3 = [...arr1, ...arr2] //arr3 ==> [1,2,3,4,5,6]
@mcanfield
Copy link

@PierBover @kelabang perhaps something like:

let list1 = [1, 2, 3];
let list2 = [4, 5, 6];

function concat(...args) {
  return args.reduce((acc, val) => [...acc, ...val]);
}

concat(list1, list2, [7, 8, 9]);
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

This utilizes the ES6 rest parameters syntax ... for the function parameters. This will create an array of arrays for as many array arguments you pass in. Not to be confused with the identical looking spread syntax which is clearly used in the reducer. Fun times 😄 ...

Note: spread syntax doesn't work with multi-dimensional arrays see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator#Copy_an_array

var a = [[1], [2], [3]];
var b = [...a];
b.shift().shift(); // 1
// Now array a is affected as well: [[], [2], [3]]

So don't try and get too fancy.

@EliecerC
Copy link

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];

arr1.push(...arr2);   
console.log(arr1) // [1, 2, 3, 4, 5, 6] 

B-)

@fi0rini
Copy link

fi0rini commented Jul 12, 2017

@EliecerC FTW

@imerkle
Copy link

imerkle commented Jul 15, 2017

@EliecerC Booyaka Booyaka 619!!

@subrata6630
Copy link

Concatenate Arrays with concat

var oldArray = [1,2,3];
var newArray = [];

var concatMe = [4,5,6];

// Only change code below this line.

newArray = oldArray;

@Ethaan
Copy link

Ethaan commented Aug 8, 2017

i'll go for.

arr1.push(...arr2);

@pensart
Copy link

pensart commented Aug 15, 2017

Lol, the Rest way, love it! Thanks!

@rcpp0
Copy link

rcpp0 commented Sep 7, 2017

@PierBover : for a generic number of arrays, an elegant way to do it :

let mergedarray = yourArrays.reduce((a, b) => [...a, ...b])

@gate3
Copy link

gate3 commented Nov 20, 2017

        const ar1 = [1,2,3]
        const ar2 = [4,5,6]
        const ar3 = [ar1, ar2]

        const ar4 = []
        ar3.forEach(a=>ar4.push(...a))
        console.log(ar4)

@Guatom
Copy link

Guatom commented Dec 1, 2017

@rcpp0: a slightly shorter version:

const mergedarray = [].concat(...yourArrays);

Greetings from _travelDevs.

@pralhadstha
Copy link

Thumbs Up to @EliecerC

@felipekm
Copy link

felipekm commented Feb 6, 2018

All possible options, nuts for ya all! :shipit:

@touhidrahman
Copy link

How to de-duplicate the merged array?

@tbekaert
Copy link

tbekaert commented Feb 28, 2018

@touhidrahman

You can use this :

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];

let concatAndDeDuplicate = (...arrs) => [ ...new Set( [].concat(...arrs) ) ];

concatAndDeDuplicate(arr1, arr2, [7, 8, 9, 2, 4]);
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

And if you have multiple arrays of potentialy identical objects, you can use this :

Be aware that it's only taking into account the key you passed in your arguments to remove duplicates !

let arr1 = [
  { id: 6, username: 'lorem' },
  { id: 8, username: 'ipsum' }
];
let arr2 = [
  { id: 6, username: 'lorem' },
  { id: 7, username: 'dolor' }
];

let concatAndDeDuplicateObjects = (p, ...arrs) => [].concat(...arrs).reduce((a, b) => !a.filter(c => b[p] === c[p]).length ? [...a, b] : a, []);

concatAndDeDuplicateObjects('id', arr1, arr2);
/*
  [
    { id: 6, username: "lorem },
    { id: 8, username: 'ipsum' },
    { id: 7, username: 'dolor' }
  ]
*/

But if a deep comparison is mandatory to you, you can do this :

let arr1 = [
  { id: 6, username: 'lorem' },
  { id: 8, username: 'ipsum' }
];
let arr2 = [
  { id: 6, username: 'dolor' },
  { id: 7, username: 'sit' }
];

let concatAndDeDuplicateObjectsDeep = (p, ...arrs) => [ ...new Set( [].concat(...arrs).map(a => JSON.stringify(a)) ) ].map(a => JSON.parse(a))

concatAndDeDuplicateObjectsDeep('id', arr1, arr2);

@eveevans
Copy link

eveevans commented Mar 7, 2018

One of the most important difference between the solutions, is that some methods doesn't mutate the original array (i.e. spread operator, or concat function) but the other mutate the original array (i.e. push).

@raynerpupo
Copy link

@eveevans exactly, that's one of the best parts from this feature, it also allows you to make array clones.

const arr1 = [1, 2, 3]; // [1, 2, 3]
const arr2 = [...arr1]; //  [1, 2, 3]
arr2[1] = 5; //                 [1, 5, 3]
console.log(arr1); //       [1, 2, 3]

@trumbitta
Copy link

const arr1 = [1, 2, 3]; // [1, 2, 3]
const arr2 = [3, 4, 5]; // [3, 4, 5]

const concatArr = [...arr1, ...arr2]; // [1, 2, 3, 3, 4, 5]
const mergedArr = Array.from(new Set([...concatArr])); // [1, 2, 3, 4, 5]

@basilbattikhi
Copy link

const arrayOne = [{ a: "a" }, { b: "b" }, { c: "c" }];
const arrayTwo = [{ d: "d" }, { e: "e" }, { f: "f" }];
const arrayMerge = { ...arrayOne, ...arrayTwo };
console.log(arrayMerge);

this will result { '0': { d: 'd' }, '1': { e: 'e' }, '2': { f: 'f' } }

How can i remove the indices and merge the array because as you see the result is only arrayTwo

@jeggu96
Copy link

jeggu96 commented Oct 23, 2018

@basilbattikhi First of all if you are trying to merge two arrays, the result will be an array(obvious).
Try this,

const arrayOne = [{ a: "a" }, { b: "b" }, { c: "c" }];
const arrayTwo = [{ d: "d" }, { e: "e" }, { f: "f" }];
const arrayMerge = [ ...arrayOne, ...arrayTwo ];
console.log(arrayMerge);

@donjosef
Copy link

donjosef commented Nov 6, 2018

I've noticed a quirk behavior with spread for flattening an array of arrays.
With concat it goes one level deeper //res = [1,2,9,3,4,5,6]

let arrays = [ [1, [2, 9,], 3], [4, [5], [6]] ];

const res = arrays.reduce((acc, curr) => {
   return acc.concat(...curr);
}, []);

This only goes one level of nesting //res = [1, [2,9], 3, 4, [5], [6]]

let arrays = [ [1, [2, 9,], 3], [4, [5], [6]] ];
const res = arrays.reduce((acc, curr) => {
    return [...acc, ...curr];
}, []);

@laukstein
Copy link

When you want to merge Objects in Array, then

[{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6, c: 7}].reduce((acc, curr) => ({...acc, ...curr}), {});

will result

{a: 5, b: 6, c: 7}

@merveillevaneck
Copy link

ddoooppppeeeeee....easiest answer ive ever googled

@lcervanteso
Copy link

This is so strange.. I rather use arr3= arr1.concat(arr2)

This way has a lot of performance issues

@tejassalasar
Copy link

_travelDevs

Thanks.. Its working. You make my day

@duhaime
Copy link

duhaime commented Nov 20, 2020

I'm getting an error jQuery is not defined?

@gyzamaz
Copy link

gyzamaz commented Apr 18, 2021

this es6 solution is also pretty cool
const concat = (...args) => args.flat();
concat([1, 2, 3], [4, 5], [6, 7]); //➞ [1, 2, 3, 4, 5, 6, 7]

@AishwaryaDomde
Copy link

I'm getting an error jQuery is not defined?

You need to add jQuery external link in script tag

@saurabh-sp-tripathi
Copy link

arr3 = [...arr1, ...arr2]; will fail if any of them are null.

@johnsusek
Copy link

const arr = [[1,2,3], [4,5,6]]
const merged = arr.reduce((a, b) => { a.splice(0, 0, b); return a; }, [])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment