Skip to content

Instantly share code, notes, and snippets.

@jamby77
Created December 16, 2020 15:19
Show Gist options
  • Save jamby77/60d62e3e468da9ff4c6eb6e5b5de8de0 to your computer and use it in GitHub Desktop.
Save jamby77/60d62e3e468da9ff4c6eb6e5b5de8de0 to your computer and use it in GitHub Desktop.
Given the input data in shape of arr1, arr2, arr3, produce array in desired format
// input
const arr1 = [
["name", "id", "age", "weight", "Cool"],
["Susan", "3", "20", "120", true],
["John", "1", "21", "150", true],
["Bob", "2", "23", "90", false],
["Ben", "4", "20", "100", true],
];
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"],
];
/*
desired output
[
["name", "id", "age", "height", "parent"],
["Susan", "3", "20", 48, ''],
....
]
*/
const idField = "id";
// make an array of unique headings entries
const finalHeadings = [...new Set([...arr1[0], ...arr2[0], ...arr3[0]])];
const resultObj = {};
// map data to id
[arr1, arr2, arr3].forEach((arr) => {
const [headings, ...data] = arr;
data.forEach((item) => {
let person = {};
let id;
for (const [index, heading] of headings.entries()) {
const val = item[index];
person[heading] = val;
if (heading === idField) {
id = val;
}
}
if(resultObj[id]) {
person = { ...resultObj[id], ...person };
}
resultObj[id] = person;
});
});
const finalResult = [
finalHeadings,
...Object.values(resultObj).map((obj) => {
return finalHeadings.map((field) => {
return obj[field] ?? '';
});
}),
];
console.table(finalResult);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment