Home > Mobile >  Match two arrays and merge them comparing key value in JavaScript
Match two arrays and merge them comparing key value in JavaScript

Time:11-05

I have two different arrays. One is like:

const arrOne = [
    [{sender: '0000', to: '1111'}],
    [{sender: '2222', to: '1111'}]
];

And the other array is like:

const arrTwo = [
  {
    firstName: 'John',
    lastName: 'Doe',
    num: '1111'
  }
]

Now i want to match the key to from arrOne and num from array two and if they mathes, the first array should update with firstname and lastname. So, the expected output would be like this:

  const arrOne = [
        [{sender: '0000', to: '1111', firstName: 'John', lastName: 'Doe'}],
        [{sender: '2222', to: '1111', firstName: 'John', lastName: 'Doe'}]
    ];

Here's what i have tried:

arrOne = arrOne.map(item => {
  const item2 = arrTwo.find(i2 => i2.num == item.to);
  return item2 ? { ...item, ...item2 } : item;
});

Thanks in advance. Also please suggest how to do that with types in TypeScript ?

CodePudding user response:

Your arrOne is an array of arrays so you need to account for that. I also assume you need to exclude num from arrTwo elements as per your expected output.

let arrOne = [
    [{sender: '0000', to: '1111'}],
    [{sender: '2222', to: '1111'}]
];

const arrTwo = [
  {
    firstName: 'John',
    lastName: 'Doe',
    num: '1111'
  }
];

arrOne = arrOne.map(item => {
  const item2 = arrTwo.find(i2 => i2.num == item[0].to);
  return item2 ? [{ ...item[0], firstName: item2.firstName, lastName: item2.lastName }] : item;
});

console.log(arrOne);

CodePudding user response:

You are almost success,just need to change item to item[0](because data in arrOne is nested array),and add [] to wrap the returned result

let arrOne = [
    [{sender: '0000', to: '1111'}],
    [{sender: '2222', to: '1111'}]
]; // it's nested array here
const arrTwo = [
  {
    firstName: 'John',
    LastName: 'Doe',
    num: '1111'
  }
]

arrOne = arrOne.map(item => {
  const item2 = arrTwo.find(i2 => i2.num == item[0].to)
  return item2 ? [{ ...item[0], ...item2 }] : [item[0]]; // need to return as array
});

console.log(arrOne)

CodePudding user response:

Just try this code,

 const arrOne = [
    [{ sender: "0000", to: "1111" }],
    [{ sender: "2222", to: "1111" }],
  ];
  const arrTwo = [
    {
      firstName: "John",
      LastName: "Doe",
      num: "1111",
    },
  ];
  const newarrtt = () => {
    let val;
    const newarry = arrOne.map(item => {
      val = arrTwo.find(x => {
        return x.num, item[0].to;
      });

      if (val) {
        return [
          {
            ...item[0],
            firstName: val.firstName,
            LastName: val.LastName,
          },
        ];
      }

      val = null;
    });
    console.log(newarry);
  };
  newarrtt();

You missed thing is,You map function is not return object ,it is array.so you need to access such as item[0].

CodePudding user response:

This technique will filter out just the unwanted 'num' property:

const arrOne = [[{sender: '0000', to: '1111'}],[{sender: '2222', to: '1111'}]];
const arrTwo = [{firstName: 'John', LastName: 'Doe',num: '1111'}];
console.log(arrOne.map(i=>[{...i[0], ...Object.fromEntries(Object.entries(
  arrTwo.find(j=>j.num===i[0].to)??{}).filter(([k,v])=>k!=='num')
    .map(([k,v])=>[k==='LastName'?'lastName':k, v]))}]));

If you need to rename the 'LastName' property to 'lastName', you can alternatively do:

const arrOne = [[{sender: '0000', to: '1111'}],[{sender: '2222', to: '1111'}]];
const arrTwo = [{firstName: 'John', LastName: 'Doe',num: '1111'}];
console.log(arrOne.map((i,o)=>[{...i[0], ...(o=(arrTwo.find(j=>j.num===i[0].to)),
    (!o?{}:{firstName: o.firstName, lastName: o.LastName}))}]));

Both techniques are resilient to situations where there is no num match found.

CodePudding user response:

A variant with forEach

const arrOne = [
   [{ sender: '0000', to: '1111' }],
   [{ sender: '2222', to: '1111' }]
];

const arrTwo = [
   {
      firstName: 'John',
      LastName: 'Doe',
      num: '1111'
   }
];

arrOne.forEach(one => {
   const item = arrTwo.find(two => Number(two.num) === Number(one[0].to));
   if(item) one[0] = { ...one[0], ...item };
});

console.log(arrOne);

  • Related