Skip to content

Instantly share code, notes, and snippets.

@andrewborisov
Created July 11, 2022 19:01
Show Gist options
  • Save andrewborisov/51014cc9064ee1f6b4784f67143f498c to your computer and use it in GitHub Desktop.
Save andrewborisov/51014cc9064ee1f6b4784f67143f498c to your computer and use it in GitHub Desktop.
const UNGROUPED_KEY = 'ungrouped';
const transformCollection = (collection, keyField) => collection.reduce((acc, curValue) => {
const DESIRED_KEY = curValue[keyField];
if (acc[`${DESIRED_KEY}`.toLowerCase()]) {
acc[`${DESIRED_KEY}`.toLowerCase()] = [...acc[`${DESIRED_KEY}`.toLowerCase()], curValue];
} else {
if (DESIRED_KEY) {
acc[`${DESIRED_KEY}`.toLowerCase()] = [curValue];
} else {
acc[UNGROUPED_KEY] = acc[UNGROUPED_KEY] ? [...acc[UNGROUPED_KEY], curValue] : [curValue];
}
}
return acc;
}, {});
console.log(transformCollection(data, 'name'));
console.log(transformCollection(data, 'unit'));
console.log(transformCollection(data, 'value'));
console.log(transformCollection(data, 'threshold'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment