Skip to content

Instantly share code, notes, and snippets.

@danscotton
Last active March 29, 2019 15:52
Show Gist options
  • Save danscotton/70fc8ea5ed41a80b3dad7bd1073b44a3 to your computer and use it in GitHub Desktop.
Save danscotton/70fc8ea5ed41a80b3dad7bd1073b44a3 to your computer and use it in GitHub Desktop.
// 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