Remove duplicates of an array of JSON objects in javascript (Angular 5)

1

I am trying to eliminate the duplicate elements inside a json object that is in an array but I can not do it, try with filter and with map but it seems that I can not access the json object, that is, I refer to it, here I show a example of the arrangement:

const q = [
  { zone: { _id: 'zone1', name: 'zone1' }, _id2: '143', name: 'ZONA1ALCALA' },
  { zone: { _id: 'zone1', name: 'zone1' }, _id2: '144', name: 'ZONA1OTRO' },
  { zone: { _id: 'zone2', name: 'zone2' }, _id2: '145', name: 'ZONA2OTRO MAS' },
  { _id: '146', name: 'ALBACETE' }
];

And what I would like is to be able to delete the zone1 dentor repeated element from the zone object that is in the array, for example I should return something like this:

const result = [
  { zone: { _id: 'zone1', name: 'zone1' }, _id2: '144', name: 'ZONA1OTRO' },
  { zone: { _id: 'zone2', name: 'zone2' }, _id2: '145', name: 'ZONA2OTRO MAS' },
  { _id: '146', name: 'ALBACETE' }
];

I would appreciate any help, I am trying in many ways all day and I still can not do it.

    
asked by albertodente 11.08.2018 в 20:31
source

2 answers

1
function removeDuplicates(arrayIn) {
    var arrayOut = [];
    arrayIn.forEach(item=> {
      try {
        if (JSON.stringify(arrayOut[arrayOut.length-1].zone) !== JSON.stringify(item.zone)) {
          arrayOut.push(item);
        }
      } catch(err) {
        arrayOut.push(item);
       }
    })
    return arrayOut;
}

with the forEach I go through the whole array and to be able to compare two JSONs I pass the JSON to string with the function JSON.stringify() and then I compare them and if there is more than one repeated element of this type zone: { _id: 'zone#', name: 'zone#' } I only add one and if the JSON does not have zona: I add it, for that it is the try - catch

    
answered by 11.08.2018 в 21:35
0

You can simplify the arrangement by using a hashtable as a cache. If you want the last duplicate to appear, you just have to reverse the arrangement. Example here:

var qcache = {};
var nuevo = q.reverse().filter(e => {
  return e.zone ? (qcache[e.zone._id] ? false : qcache[e.zone._id] = 1) : true;
}).reverse();

console.log(nuevo);
    
answered by 13.08.2018 в 13:16