var arr1 = [
{
id: 1
},{
id: 5
}
];
var arr2 = [
{
parent_id: 1
},{
parent_id: 5
}
]
[ {"id":1, "arr2":[ {"parent_id":1} ]}, {"id":5, "arr2":[ {"parent_id":5} ]} ]
const groupedArr2 = arr2.reduce((acc, n) => {
(acc[n.parent_id] = acc[n.parent_id] || []).push(n);
return acc;
}, {});
arr1.forEach(n => n.arr2 = groupedArr2[n.id] || []);
const newArr1 = arr1.map(n => ({ ...n, arr2: groupedArr2[n.id] || [] }));