mercredi 3 mars 2021

Compare two objects in an array, delete the duplicate data, and combine the different data?

I am getting a list of objects in an array, some of which are duplicates. However, the condition that produces the duplicates is different.

So picture two arrays:

var array = [{id: 1, name: 'test', condition: 'left'},
            {id: 2, name: 'example', condition: 'left'},
            {id: 1, name: 'test', condition: 'right'},
            {id: 3, name: 'foobar', condition: 'right'}]

What I am looking for:

var solution = [{id: 1, name: 'test', condition: ['left', 'right']},
                {id: 2, name: 'example', condition: 'left'},
                {id: 3, name: 'foobar', condition: 'right'}]

I am able to delete duplicates no problem using this method:

var available = result.reduce((unique, o) => {
  if (!unique.some((obj) => obj.id === o.id && obj.name === o.name)) {
    unique.push(o);
  }
  return unique;
}, []);

But would Like to combine the condition data




Aucun commentaire:

Enregistrer un commentaire