Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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]
@PierBover

This comment has been minimized.

Copy link

@PierBover PierBover commented Aug 25, 2016

So how do you make that dynamic for any number of arrays?

@Bartuz

This comment has been minimized.

Copy link

@Bartuz Bartuz commented Oct 10, 2016

haha, this comes before stackoverflow on google results. Nice, thanks, would rep up!

@steebchen

This comment has been minimized.

Copy link

@steebchen steebchen commented Oct 23, 2016

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

@mrexclamation

This comment has been minimized.

Copy link

@mrexclamation mrexclamation commented Oct 24, 2016

Lol is not strange, ITS ES6 ! 👯‍♂️

@jakeNiemiec

This comment has been minimized.

Copy link

@jakeNiemiec jakeNiemiec commented Nov 18, 2016

Thanks for this!

@pedroadame

This comment has been minimized.

Copy link

@pedroadame pedroadame commented Jan 23, 2017

Thumb up for this!

@kelabang

This comment has been minimized.

Copy link

@kelabang kelabang commented Jan 24, 2017

how to make it dynamic?

@davidraviv

This comment has been minimized.

Copy link

@davidraviv davidraviv commented Mar 12, 2017

Note that it is not a merge but rather concatenation.

const arr1 = [1,2,3];
const arr2 = [3,4,5];
const arr3 = [...arr1, ...arr2]; // arr3 ==> [1,2,3,3,4,5]
@ahmednuaman

This comment has been minimized.

Copy link

@ahmednuaman ahmednuaman commented Mar 24, 2017

Don't forget, one can do this too

const a = [1, 2, 3]
const b = [...a, 4] // b ==> [1, 2, 3, 4]
@mcanfield

This comment has been minimized.

Copy link

@mcanfield mcanfield commented Jun 21, 2017

@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

This comment has been minimized.

Copy link

@EliecerC EliecerC commented Jun 28, 2017

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

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

B-)

@fionic

This comment has been minimized.

Copy link

@fionic fionic commented Jul 12, 2017

@EliecerC FTW

@imerkle

This comment has been minimized.

Copy link

@imerkle imerkle commented Jul 15, 2017

@EliecerC Booyaka Booyaka 619!!

@subrata6630

This comment has been minimized.

Copy link

@subrata6630 subrata6630 commented Aug 3, 2017

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

This comment has been minimized.

Copy link

@Ethaan Ethaan commented Aug 8, 2017

i'll go for.

arr1.push(...arr2);

@pensart

This comment has been minimized.

Copy link

@pensart pensart commented Aug 15, 2017

Lol, the Rest way, love it! Thanks!

@rcpp0

This comment has been minimized.

Copy link

@rcpp0 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

This comment has been minimized.

Copy link

@gate3 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

This comment has been minimized.

Copy link

@Guatom Guatom commented Dec 1, 2017

@rcpp0: a slightly shorter version:

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

Greetings from _travelDevs.

@teddywest32

This comment has been minimized.

Copy link

@teddywest32 teddywest32 commented Jan 7, 2018

Thumbs Up to @EliecerC

@felipekm

This comment has been minimized.

Copy link

@felipekm felipekm commented Feb 6, 2018

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

@touhidrahman

This comment has been minimized.

Copy link

@touhidrahman touhidrahman commented Feb 21, 2018

How to de-duplicate the merged array?

@tbekaert

This comment has been minimized.

Copy link

@tbekaert 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

This comment has been minimized.

Copy link

@eveevans 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

This comment has been minimized.

Copy link

@raynerpupo raynerpupo commented Jun 15, 2018

@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

This comment has been minimized.

Copy link

@trumbitta trumbitta commented Aug 1, 2018

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

This comment has been minimized.

Copy link

@basilbattikhi basilbattikhi commented Sep 18, 2018

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

This comment has been minimized.

Copy link

@jeggu96 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

This comment has been minimized.

Copy link

@donjosef 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

This comment has been minimized.

Copy link

@laukstein laukstein commented Jan 28, 2019

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

This comment has been minimized.

Copy link

@merveillevaneck merveillevaneck commented Mar 11, 2019

ddoooppppeeeeee....easiest answer ive ever googled

@lcervanteso

This comment has been minimized.

Copy link

@lcervanteso lcervanteso commented Nov 5, 2019

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

This way has a lot of performance issues

@tejassalasar

This comment has been minimized.

Copy link

@tejassalasar tejassalasar commented Dec 2, 2019

_travelDevs

Thanks.. Its working. You make my day

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.