Last active
March 29, 2019 15:52
-
-
Save danscotton/70fc8ea5ed41a80b3dad7bd1073b44a3 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
// input | |
// [ | |
// 'pref-001|choice-001', | |
// 'pref-001|choice-002', | |
// 'pref-002|choice-001', | |
// ] | |
// output | |
// [ | |
// { reference: 'pref-001', choices: ['choice-001', 'choice-002'] }, | |
// { reference: 'pref-002', choices: ['choice-001'] }, | |
// ] | |
// solution: 3 stages | |
// | |
// 1. reduce [] into {} | |
// [ { | |
// 'pref-001|choice-001', => 'pref-001': ['choice-001', 'choice-002'], | |
// 'pref-001|choice-002', 'pref-002': ['choice-001'], | |
// 'pref-002|choice-001', } | |
// ] | |
// | |
// 2. Object.entries() to turn {} => [] so I can map | |
// { [ | |
// 'pref-001': ['choice-001', 'choice-002'], => ['pref-001', ['choice-001', 'choice-002']] | |
// 'pref-002': ['choice-001'], ['pref-002', ['choice-001']] | |
// } ] | |
// | |
// 3. map [[]] => [{}] | |
// [ [ | |
// ['pref-001', ['choice-001', 'choice-002']] => { reference: 'pref-001', choices: ['choice-001', 'choice-002'] }, | |
// ['pref-002', ['choice-001']] { reference: 'pref-002', choices: ['choice-001'] }, | |
// ] ] | |
const output = | |
Object.entries( | |
input.reduce((output, preference) => { | |
const [reference, choice] = preference.split('|'); | |
return { | |
...output, | |
[reference]: [...output[reference] || [], choice], | |
}; | |
}, {}) | |
) | |
.map(([reference, choices]) => ({ reference, choices })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment