Q
Q
Quambaras2021-06-20 17:36:04
JavaScript
Quambaras, 2021-06-20 17:36:04

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},
      ]
    ]


array to push:
const arr2 = [
      [
        {name: 'Name14', init: 1},
      ],
      [
        {name: 'Name3', init: 2},
        {name: 'Name4', init: 2},
      ]
    ]

in arr1, you need to push the objects of the arr2 array, start based on the init field. For example, arr1 contains an array at index 0, which has objects with fields init: 1, respectively, from arr2 you need to push objects into the array that also contain init: 1

, the number can be different, including arr2 can contain init: 4, which is not in arr1 and you need to create a separate array for it.
should roughly look like this:
[
      [
        {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

1 answer(s)
A
Alexey, 2021-06-20
@Azperin

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 question

Ask a Question

731 491 924 answers to any question