How to remove duplicate values from an array of objects easily?

0

I have the following array:

[  
   {  
      "value":"ETH",
      "label":"ETH"
   },
   {  
      "value":"LTC",
      "label":"LTC"
   },
   {
      "value":"ETH",
      "label":"ETH"
   }
]

As you can see, there are duplicate values. What is the best way to remove them?

I have tried to do these 2 forms, but without success:

let values = [  
   {  
      "value":"ETH",
      "label":"ETH"
   },
   {  
      "value":"LTC",
      "label":"LTC"
   },
   {
      "value":"ETH",
      "label":"ETH"
   }
]

console.log(values.filter((elem, index, self) => index === self.indexOf(elem)))

console.log([... new Set(values)])

I did not understand why the set did not work, as it tries to create a list of unique values.

    
asked by anonymous 06.05.2018 / 16:39

2 answers

1

A simple way to remove duplicates is as follows:

let values = [  
   {  
      "value":"ETH",
      "label":"ETH"
   },
   {  
      "value":"LTC",
      "label":"LTC"
   },
   {
      "value":"ETH",
      "label":"ETH"
   }
]

values = values.filter(function (a) {
	return !this[JSON.stringify(a)] && (this[JSON.stringify(a)] = true);
}, Object.create(null))

console.log(values)

Explanation:

Basically, it does iterate over the objects in the array and add its serialized value to the temporary object created in the 2nd argument as a key, and thus indicate if it has already been added by putting it true . So, when a duplicate value arrives, the conditional !this[JSON.stringify(a)] of false , not adding it to the filter.

Theoretically, if 2 objects are the same, they serialized have the same value.

Why did not Set work?

The Set compares the address of objects by default, see an example:

  let set = new Set()
  let a = {}, b = {}, c = {}
  set.add(a)
  set.add(b)
  set.add(b)
  console.log(set.size)
  console.log(set.has(a))
  console.log(set.has(b))
  console.log(set.has(c))
    
06.05.2018 / 17:07
1
var original = [{a:1}, {a:1}, {a:2}, {a:3}, {a:1}, {a:2}, {a:5}];
var reduced = [];

original.forEach((item) => {
    var duplicated  = reduced.findIndex(redItem => {
        return item.a == redItem.a;
    }) > -1;

    if(!duplicated) {
        reduced.push(item);
    }
});

console.log(JSON.stringify(reduced));
    
13.09.2018 / 22:55