Last active
December 12, 2020 15:05
-
-
Save waspeer/4e0531d4f701e9f2773c9fb8080a8250 to your computer and use it in GitHub Desktop.
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
const arr1 = [ | |
['name', 'id', 'age', 'weight'], | |
['Susan', '3', '20', '120'], | |
['John', '1', '21', '150'], | |
['Bob', '2', '23', '90'], | |
['Ben', '4', '20', '100'], | |
]; | |
const arr2 = [ | |
['name', 'id', 'height'], | |
['Bob', '2', '50'], | |
['John', '1', '45'], | |
['Ben', '4', '43'], | |
['Susan', '3', '48'], | |
]; | |
const arr3 = [ | |
['name', 'id', 'parent'], | |
['Bob', '2', 'yes'], | |
['John', '1', 'yes'], | |
]; | |
function parseCsvArray(array) { | |
const [headings, ...rows] = array; | |
return rows.map((cols) => { | |
const entries = cols.map((col, index) => [headings[index], col]); | |
return Object.fromEntries(entries); | |
}); | |
} | |
function mergeById(rows) { | |
const ids = new Set(rows.map(({ id }) => id)); // All unique ids | |
return [...ids].map((currentId) => { | |
const dataForId = rows.filter(({ id }) => id === currentId); | |
return dataForId.reduce((acc, row) => ({ ...acc, ...row })); | |
}); | |
} | |
const allData = [ | |
...parseCsvArray(arr1), | |
...parseCsvArray(arr2), | |
...parseCsvArray(arr3), | |
]; | |
console.log(mergeById(allData)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment