It is clever to try to use a set, because sets do avoid duplication, but unfortunately they only work in the way you intended if the element is a primitive data type such as String or Number, and not if it is an object, i.e. of the form { key: value, ... }.
If the element is just a string, e.g. "Bob", because two strings "Bob" and "Bob" are considered identical by the Set, and so will be entered as a single element.
However, if your element is an object, e.g. {name: "Bob"}, then two elements defined separately as {name: "Bob"} and {name: "Bob"} will be considered unequal, so will be entered as two different elements in the Set.
Initialise like this:
userStories = {}
And then for each entry:
userStories[user_id]=({
avatar: storie.user.avatar,
});
This way, you end up with this structure:
userStories: {
1234: { avatar: "abc.jpg" },
1258: { avatar: "def.jpg" },
etc
}
You can use this Object structure in much the way you were using the Set, with two advantages:
(a) If you put in two identical entries such as 1234: { avatar: "abc.jpg" }, only one will be stored.
(b) You can directly access the avatar of any one person, by their id. (With the Set, you would still have to somehow search the elements to find the right one.)
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.
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