Last active
July 20, 2023 00:44
-
-
Save gnowland/2aec99dffc21476487596c122da6d2ed to your computer and use it in GitHub Desktop.
elegantly reduce objects (aka collator/collate)
This file contains hidden or 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
// 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