Home > Back-end >  Why is Set() repeating values?
Why is Set() repeating values?

Time:07-09

I´m trying to use Set() in js to retrieve some 'unique data', but it keeps returning repeated values to me.

Console debug: Console debug

Code:

userStories.add({
   user_id: storie.user_id,
   avatar: storie.user.avatar,
});

CodePudding user response:

Objects in JavaScript are reference types, which means that when you create a new object in your function, JavaScript thinks they are different (even when they have the same values).

From the article:

If they’re distinct objects, even if they contain identical properties, the comparison will result in false.

var arr1 = ['Hi!'];
var arr2 = ['Hi!'];
console.log(arr1 === arr2); // -> false

CodePudding user response:

The Set object lets you store unique values of any type, whether primitive values or object references not just objects. See reference MDN

const mySet = new Set();
const object1 = {a:1, b:1};
mySet.add(object1);
mySet.add(object1);
console.log(mySet); // The set will be having only 1 entry as both the times we added the same reference of object1.

However if you do try to insert different references of object the set keeps on adding the objects.For example:

const mySet = new Set();
const object1 = {a:1, b:1};
mySet.add(object1);
mySet.add({a:1,b:1}); // This is a new object not the object1
console.log(mySet); It will have 2 entries

Not only objects same goes with Arrays if you try to do like above.

  • Related