Created
June 21, 2022 20:08
-
-
Save Zerquix18/f774bb796cb189ecf0bf135e077d2625 to your computer and use it in GitHub Desktop.
This file contains 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", "country"], | |
["Susan", "3", "20", "mali"], | |
["John", "1", "21", "chad"], | |
["Jose", "2", "23", "oman"], | |
["Alex", "4", "20", "fiji"], | |
]; | |
const arr2 = [ | |
["name", "id", "height"], | |
["Jose", "2", "50"], | |
["John", "1", "45"], | |
["Alex", "4", "43"], | |
["Susan", "3", "48"], | |
]; | |
const arr3 = [ | |
["name", "id", "parent"], | |
["Susan", "3", "yes"], | |
["John", "1", "yes"], | |
]; | |
const arr4 = [ | |
["name", "id", "isCool"], | |
["Alex", "4", true], | |
["John", "1", true], | |
["Susan", "3", true], | |
["Jose", "2", true] | |
]; | |
// turns one of the arr1, arr2, etc., into an array of objects | |
function parseList(items) { | |
const result = []; | |
const headers = items.shift(); | |
items.forEach((cells) => { | |
const item = {}; | |
cells.forEach((value, index) => { | |
const key = headers[index]; | |
item[key] = value; | |
}); | |
result.push(item); | |
}); | |
return result; | |
} | |
// adds one of the results of parseList (an object) into the list array - checks if it exists first | |
// if it does, merges both objects, otherwise adds a new item to the list | |
function appendToList(list, object) { | |
const index = list.findIndex(item => item.id === object.id); | |
if (index === -1) { | |
list.push(object); | |
} else { | |
list[index] = { ...list[index], ...object }; | |
} | |
return list; | |
} | |
// takes all lists as parameters and builds the final result | |
function buildList(...items) { | |
const objects = items.map(item => parseList(item)).flat(); | |
let result = []; | |
objects.forEach(object => { | |
result = appendToList(result, object); | |
}); | |
result.sort((a, b) => a.id - b.id); | |
return result; | |
} | |
buildList(arr1, arr2, arr3, arr4); | |
/* | |
[ | |
{ "name": "John", "id": "1", "age": "21", "country": "chad", "height": "45", "parent": "yes", "isCool": true }, | |
{ "name": "Jose", "id": "2", "age": "23", "country": "oman", "height": "50", "isCool": true }, | |
{ "name": "Susan", "id": "3", "age": "20", "country": "mali", "height": "48", "parent": "yes", "isCool": true }, | |
{ "name": "Alex", "id": "4", "age": "20", "country": "fiji", "height": "43", "isCool": true } | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment