Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to combine tow array and remove duplicate object from array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading