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