Skip to content

Instantly share code, notes, and snippets.

@geomago
Last active June 18, 2020 16:17
Show Gist options
  • Save geomago/72058abeb2d99e33b35498edc05c88f6 to your computer and use it in GitHub Desktop.
Save geomago/72058abeb2d99e33b35498edc05c88f6 to your computer and use it in GitHub Desktop.
group_by
let grouped = cars.reduce(
(groups, curr) => {
let key = curr.make;
if (groups[key]===undefined) {
groups[key] = {count:1, minPrice:curr.price, maxPrice: curr.price };
} else {
groups[key].count++;
groups[key].minPrice = Math.min(groups[key].minPrice, curr.price);
groups[key].maxPrice = Math.max(groups[key].maxPrice, curr.price);
}
return groups;
},
{}
);
// RESULT IS
{
Ferrari: {
count: 5,
minPrice: 262000,
maxPrice: 336000
},
Lamborghini: {
count: 1,
minPrice: 329400,
maxPrice: 329400
},
Bugatti: {
count: 2,
minPrice: 3000000,
maxPrice: 3000000
},
McLaren: {
count: 1,
minPrice: 203000,
maxPrice: 203000
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment