Home > front end >  How to combine tow array and remove duplicate object from array
How to combine tow array and remove duplicate object from array

Time:11-18

I have two arrays like this and I have filtered these two arrays and combined them in a final array and remove the duplicate value and keep the one

let arr1 = [
  {
    name : 'abc',
    std: '1'
  },
  {
    name : 'abc1',
    std: '2'
  },
  {
    name : 'abc2',
    std: '3'
  },
]
let arr2 = [
  {
    name : 'abc3',
    std: '1'
  },
  {
    name : 'abc4',
    std: '2'
  },
  {
    name : 'abc2',
    std: '3'
  },
]

expected output like I want abc2 get only one time

let finalArr = [
  {
    name : 'abc',
    std: '1'
  },
  {
    name : 'abc1',
    std: '2'
  },
  {
    name : 'abc2',
    std: '3'
  },
  {
    name : 'abc3',
    std: '1'
  },
  {
    name : 'abc4',
    std: '2'
  },
]

so can anyone help me out with how can I do that I tried many ways but not working and som time I got error.

CodePudding user response:

You could use a Set for the given name and filter merged array with the set.

let arr1 = [{name : 'abc',std: '1'},{name : 'abc1',std: '2'},{ name : 'abc2', std: '3'}]

let arr2 = [{name : 'abc3', std: '1' }, { name : 'abc4', std: '2' }, {name : 'abc2', std: '3'}]

const names = new Set(arr1.map(({name}) => name));
const filteredArray = [...arr1, ...arr2.filter(({name}) => !names.has(name))];


console.log(filteredArray)
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Ids should be unique in the array

arr.reduce((acc, current) => {
  const x = acc.find(item => item.id === current.id);
  if (!x) {
    return acc.concat([current]);
  } else {
    return acc;
  }
}, []);

CodePudding user response:

There's an other way too, you have options :)

const arr1 = [{
  name: 'abc',
  std: '1'
}, {
  name: 'abc1',
  std: '2'
}, {
  name: 'abc2',
  std: '3'
}, ]
const arr2 = [{
  name: 'abc3',
  std: '1'
}, {
  name: 'abc4',
  std: '2'
}, {
  name: 'abc2',
  std: '3'
}, ]

function mapper(v) {
  return [v.name, v]
};
const map = new Map(arr1.map(mapper).concat(arr2.map(mapper)));
console.log([...map.values()])
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related