Home > Mobile >  Union of two-dimensional arrays by value
Union of two-dimensional arrays by value

Time:07-28

Good afternoon. I'm new and just learning. Please help me to solve the problem with array merging. i hav 2 arrays

let arr1 = [['boss',, 'boss I.V.', '5552654','card 100'],
            ['ard',, 'ard J.B.', '3722654','card 520'],
            ['Jon',, 'Jon sviss', '394554','card 22120'],
            ['Elty B',, 'Elty Bitry B.', '12265664', 'card 9990'],
            ['Elty B.I',, 'Elty Bitry I.','3322654', 'card 002200']];

let arr2 = [['boss', 3000, 'comm1'],
            ['Elty B', 8000.500, 'comm2']];
//-------------------------------------------- 
         //I need to get:

let arrR = [[1,'boss I.V.', '5552654', 'card 100', 3000, 'comm1'],
            [2,'Elty Bitry B.', '12265664', 'card 9990', 8000.500, 'comm2']];
//--------------------------------------------
          // i made it a loop 'for':

  arr1 = arr1.filter( (item) => arr2.find((el) => el[0] === item[0])).sort();
  for (var i = 0; i<arr1.length; i  ) {                    
    arr1[i].push(arr2[i][1],arr2[i][2]);
    arr1[i].splice(0,1);
    arr1[i][0] = i 1;
  }
  return arr1;
//--------------------------------------------
           //it is not right (((

how to do it correctly by finding by value: " if (arr1[i][0] === arr2[k][0]) " and don't use a loop?

CodePudding user response:

const arrR = arr2.map((e, i, a) => {
  const ra = arr1.find(item => item[0] === e[0]);
  return [i   1, ...ra.splice(2), ...e.splice(1)];
});

Since the resulting array has the same number of entries as arr2 I am calling map on arr2.

CodePudding user response:

you have to add commas in your arr1 statement and add the bracket at the end of the arr2 statement and remove the sort() function.

  • Related