-4

lets say we have an array of objects:

results = [
{id: 1, name: John}, 
{id: 2, name: Gabo}, 
{id: 1, name: Anna}, 
{id: 3, name: Gabo}
{id: 1, name: Jack}, ]

I want function which gets all this objects which has unique id and name and it's value is not in other object.

results = [
{id: 1, name: John}, // unique id-name so we add to array
{id: 2, name: Gabo},  // unique id-name so we add to array
{id: 1, name: Anna},  // name is unique but object with this id already exists in array so we reject
{id: 3, name: Gabo}  // id is unique but object with this name already exists in array so we reject
{id: 1, name: Jack}, ] //etc..
results = [
{id: 1, name: John}, 
{id: 2, name: Gabo}, 
tiagon
  • 1

1 Answers1

1

You can use Set to register and then quickly check for duplicate id or name:

function getUniq(items) {
    const ids = new Set();
    const names = new Set();

    return items.filter((item) => {
        if (ids.has(item.id) || names.has(item.name)) {
            return false;
        }

        ids.add(item.id);
        names.add(item.name);

        return true;
    });
}
z1ne2wo
  • 278
  • 1
  • 7