Last active
December 12, 2020 18:14
-
-
Save ograu/aa31d1ceae4254fd1eaf4a96d0b66e49 to your computer and use it in GitHub Desktop.
Wes Bos tricky JS array problem
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
import _ from 'lodash'; | |
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'], | |
]; | |
// 1. convert arrays of array into collections | |
// 2. merge them | |
// Vanilla solution | |
function arrayToCollection(arr) { | |
const [keys, ...values] = arr; | |
// This creates [key, value] pairs. | |
const keysWithValues = values.map(person => { | |
return person.map((value, i) => ([keys[i], value])); | |
}); | |
// This creates an object from key/value pairs. | |
return keysWithValues.map(p => Object.fromEntries(p)); | |
} | |
// 1 | |
const collection1 = arrayToCollection(arr1); | |
const collection2 = arrayToCollection(arr2); | |
const collection3 = arrayToCollection(arr3); | |
// 2 | |
const ids = Array.from( | |
new Set([...collection1, ...collection2, ...collection3].map(p => p.id)), | |
).sort() | |
const mergedCollection = ids | |
.reduce((acc, id, i) => { | |
// Not checking if the index exists because spreading undefined doesn't trigger an error. | |
const person = { | |
...collection1.find(p => p.id === id), | |
...collection2.find(p => p.id === id), | |
...collection3.find(p => p.id === id), | |
}; | |
return [...acc, person]; | |
}, []); | |
console.table(mergedCollection); | |
// Lodash solution for (2) (stolen from https://stackoverflow.com/a/42740020/7179235 ) | |
const m = _(collection1) | |
.concat(collection2) | |
.concat(collection3) | |
.groupBy('id') | |
.map(_.spread(_.merge)) | |
.value(); | |
console.table(m); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment