Skip to content

Instantly share code, notes, and snippets.

@selimsevencan
Created December 24, 2019 09:12
Show Gist options
  • Save selimsevencan/1853c995358c523d071e7481a8711788 to your computer and use it in GitHub Desktop.
Save selimsevencan/1853c995358c523d071e7481a8711788 to your computer and use it in GitHub Desktop.
reduce function
const posts = [
{
id: '1',
name: 'Post 1',
author: {
id: '1',
name: 'Author 1'
},
},
{
id: '2',
name: 'Post 2',
author: {
id: '1',
name: 'Author 1'
},
},
{
id: '3',
name: 'Post 3',
author: {
id: '2',
name: 'Author 2'
}
},
{
id: '4',
name: 'Post 4',
author: {
id: '2',
name: 'Author 2'
}
},
{
author: {
id: '3',
name: 'Author 3'
}
}
];
const authors = posts.reduce((mem, input) => {
mem[input.author.id] = {
author: {
id: input.author.id,
name: input.author.name
},
...(input.id
? {
posts: [
...(mem[input.author.id] ? mem[input.author.id].posts : []),
{
id: input.id,
name: input.name
}
]
}
: {})
};
return mem;
}, {});
console.log(authors);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment