Home > database >  Removing not matching obj from old array and replace matching obj from new array with old matching o
Removing not matching obj from old array and replace matching obj from new array with old matching o

Time:10-26

I cant figure out how to do this...

const arr1 = [{ name: 'peter' }, { name: 'sam', id: 1 }, { name: 'mark' }];
const arr2 = [{ name: 'sam' }, { name: 't' }, { name: 'george' }];

Desired outcome:

const arr2 = [{ name: 'sam', id: 1 }, { name: 't' }, { name: 'george' }];

CodePudding user response:

If you want the previous item I would do this:

const arr1 = [{
  name: 'peter'
}, {
  name: 'sam',
  id: 1
}, {
  name: 'mark'
}];
const arr2 = [{
  name: 'sam'
}, {
  name: 't'
}, {
  name: 'george'
}];

const result = arr2.map(item => {
  const previousItem = arr1.find(i => i.name === item.name)
  if (previousItem) {
    return previousItem
  }
  return item
})

console.log(result);

However, if you want to combine the old and new data, I would recommend spreading the data together, like so:

const arr1 = [{
  name: 'peter'
}, {
  name: 'sam',
  id: 1
}, {
  name: 'mark'
}];
const arr2 = [{
  name: 'sam'
}, {
  name: 't'
}, {
  name: 'george'
}];

const result = arr2.map(item => {
  const previousItem = arr1.find(i => i.name === item.name)
  if (previousItem) {
    return {
      ...previousItem,
      ...item
    }
  }
  return item
})

console.log(result);

Both allude to the same result here, but you would get different results if arr2's "Sam" object had an additional key "age" on it... In this example, the second snippet would keep the "age" key because the spread (...) operation combines the two objects together.

CodePudding user response:

You can try this.

const arr1 = [{ name: 'peter' }, { name: 'sam', id: 1 }, { name: 'mark' }];
const arr2 = [{ name: 'sam' }, { name: 't' }, { name: 'george' }];

const result = [];
const res1 = arr2.map((item, i) => {
  let index = arr1.findIndex((x) => x.name === item.name);
  if ( index > -1 )
    result.push(arr1[index]);
  else
    result.push(item);
})

console.log(result);
  • Related