Last active
May 13, 2025 01:02
-
-
Save chadoh/134470bfa50fd153153fe8082ba7b540 to your computer and use it in GitHub Desktop.
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
const links = [ | |
{ name: 'pablo', category: 'cat' }, | |
{ name: 'harper', category: 'cat' }, | |
{ name: 'phyllis', category: 'dog' }, | |
{ name: 'derp', category: 'snake' }, | |
] | |
// option 1: "oops, forgot the snakes" | |
const catLinks = [] | |
const dogLinks = [] | |
links.forEach(link => { | |
if (link.category === 'cat') catLinks.push(link) | |
if (link.category === 'dog') dogLinks.push(link) | |
}) | |
// option 2: let's reduce 💪 | |
const transformedGoal = { | |
cat: [ | |
{ name: 'pablo', category: 'cat' }, | |
{ name: 'harper', category: 'cat' }, | |
], | |
dog: [ | |
{ name: 'phyllis', category: 'dog' } | |
], | |
snake: [ | |
{ name: 'derp', category: 'snake' }, | |
], | |
} | |
const transformed = links.reduce( | |
(acc, link) => { | |
acc[link.category] = [...acc[link.category], link] | |
return acc | |
}, | |
{} as Record<string, (typeof links[0])[]> | |
) | |
// @ts-expect-error didn't import it | |
assertDeepEqual(transformedGoal, transformed) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment