Skip to content

Instantly share code, notes, and snippets.

@waspeer
Last active December 12, 2020 15:05
Show Gist options
  • Save waspeer/4e0531d4f701e9f2773c9fb8080a8250 to your computer and use it in GitHub Desktop.
Save waspeer/4e0531d4f701e9f2773c9fb8080a8250 to your computer and use it in GitHub Desktop.
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