4

I have an array of objects, and I am trying t get unique elements from it. I tried using Set to get unique elements. It doesn't work in case of array of objects, but does work in case of array of strings etc.

How can I achieve this using set?

let data =[{"name":"tagName2"},{"name":"tagName2"}];
console.log(data);  //[ { name: 'tagName2' }, { name: 'tagName2' } ]
console.log((new Set(data)));  //Set { { name: 'tagName2' }, { name: 'tagName2' } }
7
  • 3
    Those are two different objects. Objects are equal only when they reference to same location. Commented Jul 19, 2017 at 5:11
  • 1
    There's no interface you can override to establish equivalence - it's plain old javascript for now. Commented Jul 19, 2017 at 5:13
  • Easy to check: ({ name: 'tagName2' }) == ({ name: 'tagName2' }) yields false. Commented Jul 19, 2017 at 5:16
  • define the objects outside the array and push it Commented Jul 19, 2017 at 5:22
  • @azad the data actually comes from an API request in that format Commented Jul 19, 2017 at 5:23

2 Answers 2

3

You can filter the array with unique objects first and then pass it to Set as shown below:

let data =[{"name":"tagName2"},{"name":"tagName2"}];

uniqueData=removeDuplicates(data, "name");

console.log((new Set(uniqueData)));  //Set {{ name: 'tagName2' }}

function removeDuplicates(data, param){
    return data.filter(function(item, pos, array){
        return array.map(function(mapItem){ return mapItem[param]; }).indexOf(item[param]) === pos;
    })
}
Sign up to request clarification or add additional context in comments.

Comments

2

From the docs

The Set object lets you store unique values of any type, whether primitive values or object references

As pointed out by @Tushar those two objects are different. Set filter outs objects that are refrencing to the same object.

For Set to work you need to pass in two objects refrencing the same object.Check out this fiddle.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.