Переделать массив при помощи reduce
Приходит такой массив
(можно переделать при помощи map, желательно самый оптимальный способ)
const arr = [
{id: null, status: true, comment: ''},
{id: null, status: true, comment: ''},
{id: 1, status: true, comment: ''},
{id: 1, status: true, comment: ''},
{id: 1, status: true, comment: ''},
{id: 2, status: true, comment: ''},
]
Необходимо переделать в такой:
const result = [
{id: null, arr: [
{id: null, status: true, comment: ''},
{id: null, status: true, comment: ''},
]},
{id: 1, arr: [
{id: 1, status: true, comment: ''},
{id: 1, status: true, comment: ''},
{id: 1, status: true, comment: ''},
]},
{id: 2, arr: [
{id: 2, status: true, comment: ''},
]}
]
Ответы (1 шт):
Автор решения: entithat
→ Ссылка
const arr = [
{id: null, status: true, comment: ''},
{id: null, status: true, comment: ''},
{id: 1, status: true, comment: ''},
{id: 1, status: true, comment: ''},
{id: 1, status: true, comment: ''},
{id: 2, status: true, comment: ''},
];
console.log(
arr.reduce((acc, cur) => {
let idx = acc.findIndex(e => e.id === cur.id);
if (idx !== -1) acc[idx].arr.push(cur);
else acc.push({ id: cur.id, arr: [cur] });
return acc;
}, [])
);