Created
January 7, 2021 12:22
-
-
Save ahamed/d49f6444ea3c1d4c9a768a8e5bdbd8a1 to your computer and use it in GitHub Desktop.
Merging two or more arrays by making unique by a list of keys.
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
| /** | |
| * Merge two or more same structured arrays of objects | |
| * and make them unique by user provided keys. | |
| * | |
| * @author Sajeeb Ahamed | |
| */ | |
| const mergeArrays = (...arrays) => { | |
| // Consider the last argument as the keys | |
| const keys = arrays.pop(); | |
| const result = {}; | |
| arrays.forEach(array => | |
| array.forEach(item => { | |
| const key = keys.map(i => item[i]).join('-'); | |
| result[key] = item; | |
| }) | |
| ); | |
| return Object.values(result); | |
| }; | |
| const array1 = [{ name: 'John Doe', age: 25 },{ name: 'Alice', age: 25 },{ name: 'Bob', age: 20 }]; | |
| const array2 = [{ name: 'John Joe', age: 25 },{ name: 'Alice', age: 30 },{ name: 'Bob', age: 20 }]; | |
| const output = mergeArrays(array1, array2, ['age']); | |
| console.log(output); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment