Looking for more optimized way to do it.
Resource arrays:
const users = [
{ id: 1, name: 'Vasya', postIds: [11, 22] },
{ id: 2, name: 'Petya', postIds: [33] },
{ id: 3, name: 'Roma', postIds: [44] },
];
const posts = [
{ id: 11, title: 'How to eat' },
{ id: 22, title: 'How to drink' },
{ id: 33, title: 'How to breath' },
{ id: 44, title: 'How to swim' },
];
Expected result
const expectedResult = [
{
id: 1,
name: 'Vasya',
posts: [
{ id: 11, title: 'How to eat' },
{ id: 22, title: 'How to drink' },
]
},
{
id: 2,
name: 'Petya',
posts: [{ id: 33, title: 'How to breath' },]
},
{
id: 3,
name: 'Roma',
posts: [{ id: 44, title: 'How to swim' }]
},
]
What i am doing:
const expectedOutput = users.map(({id,name,postIds})=>({id,name,posts:posts.filter(post=>postIds.includes(post.id))}))
The problem is - i am doing too many iterations (map, filter and includes), thinking that, there is a possibility to do it in a more pretty way. Will be greatful for any ideas for refactoring