1

Is there a way to check if the objects have the same that before inserting them into the Set?

let mySet = new Set();

let person = {
  name: 'John',
  age: 21
};

let person2 = {
  name: 'John',
  age: 21
};

mySet.add(person);

mySet.add(person2);

console.log(JSON.stringify([...mySet])); 
asfafafags
  • 99
  • 5
  • 2
    It's because in the second set you're not adding the same object, but two different objects with the same property and value. You could also evaluate this with `===` to see if the two objects are the same. `Set` uses the same principle. [See here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#value_equality) – Emiel Zuurbier Sep 13 '22 at 10:38
  • Does this answer your question? [How to determine equality for two JavaScript objects?](https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) – Emiel Zuurbier Sep 13 '22 at 10:56

1 Answers1

0

Is there a way to check if the objects have the same that before inserting them into the Set?

Only by doing it yourself by iterating the set, since they're different (though equivalent) objects; as is always the case, two different objects aren't "equal" to each other for any of JavaScript's built-in operations. And sets don't offer methods like some or find like arrays do.

For instance, you might use a utility function:

function setFind(set, predicate) {
    for (const element of set) {
        if (predicate(element)) {
            return element;
        }
    }
}

Then:

if (!setFind(mySet, ({ name, age }) => name === person2.name && age == person2.age)) {
    mySet.add(person2);
}

let mySet = new Set();

let person = {
    name: 'John',
    age: 21
};

let person2 = {
    name: 'John',
    age: 21
};

mySet.add(person);

if (!setFind(mySet, ({ name, age }) => name === person2.name && age == person2.age)) {
    mySet.add(person2);
}

console.log(JSON.stringify([...mySet]));

function setFind(set, predicate) {
    for (const element of set) {
        if (predicate(element)) {
            return element;
        }
    }
}

Or just use a loop, or use some or find after converting to an array:

let contains = [...mySet].some(({ name, age }) => name === person2.name && age == person2.age);
if (!contains) {
    mySet.add(person2);
}

let mySet = new Set();

let person = {
    name: 'John',
    age: 21
};

let person2 = {
    name: 'John',
    age: 21
};

mySet.add(person);

let contains = [...mySet].some(({ name, age }) => name === person2.name && age == person2.age);
if (!contains) {
    mySet.add(person2);
}

console.log(JSON.stringify([...mySet]));

Or similar.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875