Skip to content

Instantly share code, notes, and snippets.

@gnowland
Last active July 20, 2023 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gnowland/2aec99dffc21476487596c122da6d2ed to your computer and use it in GitHub Desktop.
Save gnowland/2aec99dffc21476487596c122da6d2ed to your computer and use it in GitHub Desktop.
elegantly reduce objects (aka collator/collate)
// Elegantly reduce array of objects into an object labeled by the value of a specific property
// Source: https://vmarchesin.medium.com/using-array-prototype-reduce-in-objects-using-javascript-dfcdae538fc8
interface Person {
name: string;
year: number;
sign: "Aries" | "Taurus" | "Gemini" | "Cancer" | "Leo" | "Virgo" | "Libra" | "Scorpio" | "Sagittarius" | "Capricorn" | "Aquarius" | "Pisces";
}
const people: Person[] = [
{name: "Gifford", year: 1988, sign: "Taurus"},
{name: "Liz", year: 1994, sign: "Taurus"},
{name: "Heather", year: 1987, sign: "Pisces"}
]
// Make an object whos keys are zodiac signs (e.g. "Taurus") and values are an array of objects matching that zodiac sign
const organized = people.reduce((map, person) => ({
...map,
[person.sign]: [...map[person.sign] || [], person],
}), {} as Record<string, Person[]>)
console.log(organized)
// {
// "Taurus": [
// {
// "name": "Gifford",
// "year": 1988,
// "sign": "Taurus"
// },
// {
// "name": "Liz",
// "year": 1994,
// "sign": "Taurus"
// }
// ],
// "Pisces": [
// {
// "name": "Heather",
// "year": 1987,
// "sign": "Pisces"
// }
// ]
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment