Delete an array of duplicate objects in javascript

6

How to remove duplicate data from an array of objects?:

example:

var array = [
  {id:1,nombre:'casa'},
  {id:2,nombre:'fruta'},
  {id:3,nombre:'mascotas'},
  {id:1,nombre:'casa'},
  {id:2,nombre:'fruta'},
  {id:4,nombre:'cosas'},
  {id:5,nombre:'otros'}
];
    
asked by Albert Arias 27.12.2016 в 18:44
source

3 answers

4

Here you have solutions that could be useful for your Array.

Try this way:

var arrayWithDuplicates = [
    {"type":"LICENSE", "licenseNum": "12345", state:"NV"},
    {"type":"LICENSE", "licenseNum": "A7846", state:"CA"},
    {"type":"LICENSE", "licenseNum": "12345", state:"OR"},
    {"type":"LICENSE", "licenseNum": "10849", state:"CA"},
    {"type":"LICENSE", "licenseNum": "B7037", state:"WA"},
    {"type":"LICENSE", "licenseNum": "12345", state:"NM"}
];

function removeDuplicates(originalArray, prop) {
     var newArray = [];
     var lookupObject  = {};

     for(var i in originalArray) {
        lookupObject[originalArray[i][prop]] = originalArray[i];
     }

     for(i in lookupObject) {
         newArray.push(lookupObject[i]);
     }
      return newArray;
 }

var uniqueArray = removeDuplicates(arrayWithDuplicates, "licenseNum");
console.log("uniqueArray is: " + JSON.stringify(uniqueArray));

You can also try like this:

var arr = {};

for ( var i=0, len=things.thing.length; i < len; i++ )
    arr[things.thing[i]['place']] = things.thing[i];

things.thing = new Array();
for ( var key in arr )
    things.thing.push(arr[key]);
    
answered by 27.12.2016 / 18:48
source
10

You could use Array.prototype.filter() ( IE9+ )

Example:

var array = [
  {id:1,nombre:'casa'},
  {id:2,nombre:'fruta'},
  {id:3,nombre:'mascotas'},
  {id:1,nombre:'casa'},
  {id:2,nombre:'fruta'},
  {id:4,nombre:'cosas'},
  {id:5,nombre:'otros'}
];

var hash = {};
array = array.filter(function(current) {
  var exists = !hash[current.id] || false;
  hash[current.id] = true;
  return exists;
});

console.log(JSON.stringify(array));
    
answered by 27.12.2016 в 19:06
2

You could use the object Set ()

  

Set objects are collections of values. You can iterate its elements in the order of their insertion. A value in a Set can only be once; This one is unique in the Set collection.

let array = [
  { id: 1, nombre: 'casa' },
  { id: 2, nombre: 'fruta' },
  { id: 3, nombre: 'mascotas' },
  { id: 1, nombre: 'casa' },
  { id: 2, nombre: 'fruta' },
  { id: 4, nombre: 'cosas' },
  { id: 5, nombre: 'otros' }
];

let set                 = new Set( array.map( JSON.stringify ) )
let arrSinDuplicaciones = Array.from( set ).map( JSON.parse );

console.log( arrSinDuplicaciones );
    
answered by 18.10.2018 в 00:01