-
-
Save obonyojimmy/c2d7209ca75479c78bb78cbef7379072 to your computer and use it in GitHub Desktop.
Merge Arrays in one with ES6 Array spread
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment