Answer the question
In order to leave comments, you need to log in
How to push one array with arrays into another, according to the desired values of the object?
there is a first array to push into
const arr1 = [
[
{name: 'Name11', init: 1},
{name: 'Name12', init: 1},
{name: 'Name13', init: 1}
],
[
{name: 'Name1', init: 2},
{name: 'Name2', init: 2},
],
[
{name: 'Name111', init: 3},
{name: 'Name222', init: 3},
]
]
const arr2 = [
[
{name: 'Name14', init: 1},
],
[
{name: 'Name3', init: 2},
{name: 'Name4', init: 2},
]
]
[
[
{name: 'Name11', init: 1},
{name: 'Name12', init: 1},
{name: 'Name13', init: 1},
{name: 'Name14', init: 1}
],
[
{name: 'Name1', init: 2},
{name: 'Name2', init: 2},
{name: 'Name3', init: 2},
{name: 'Name4', init: 2}
],
[
{name: 'Name111', init: 3},
{name: 'Name222', init: 3},
]
]
Answer the question
In order to leave comments, you need to log in
In order not to look for indexes, you can simply map them
let initToIndex = arr1.reduce((acc, item, idx) => {
acc[item[0].init] = idx;
return acc;
}, {});
arr2.flat().forEach(x => {
let idx = initToIndex[x.init];
if (!initToIndex.hasOwnProperty(x.init)) {
idx = arr1.push([]) - 1;
initToIndex[x.init] = idx;
};
arr1[idx].push(x);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question