-1

I have requirement where I need to check duplicates for object items.

In the below Array of object, I need to check for "empno" OR "extension" and If there are any duplicates then I need to throw an error.

I have tried this Stack Overflow link but it didn't work for me.

[
    {
        "id": 269,
        "empno": "34567",
        "extension": 345
    },
    {
        "id": 269,
        "empno": "34568",
        "extension": 346
    },
    {
        "id": 269,
        "empno": "34569",
        "extension": 345
    },
    {
        "id": 269,
        "empno": "34567",
        "extension": 345
    }
]

1 Answer 1

1

You could build a Set to allow for efficient lookups of existing values:

const hasDuplicates = (data) => {
  const set = new Set();

  for (let {empno, extension} of data) {
    const key = `${empno}/${extension}`;
    if (set.has(key)) {
      return true;
    }

    set.add(key);
  }

  return false;
};

Full snippet:

const data = [{
    "id": 269,
    "empno": "34567",
    "extension": 345
  },
  {
    "id": 269,
    "empno": "34568",
    "extension": 346
  },
  {
    "id": 269,
    "empno": "34569",
    "extension": 345
  },
  {
    "id": 269,
    "empno": "34567",
    "extension": 345
  }
];

const hasDuplicates = (data) => {
  const set = new Set();
  
  for (let {empno, extension} of data) {
    const key = `${empno}/${extension}`;
    if (set.has(key)) {
      return true;
    }
    
    set.add(key);
  }
  
  return false;
};

console.log(hasDuplicates(data));


If you want something less verbose at the cost of processing the entire array even if duplicates have already been found, you can reduce to a Set and compare its size with the original array:

const hasDuplicates = (data) => data.length !== data.reduce((a, {empno, extension}) => a.add(`${empno}/${extension}`), new Set).size;

Full snippet:

const data = [{
    "id": 269,
    "empno": "34567",
    "extension": 345
  },
  {
    "id": 269,
    "empno": "34568",
    "extension": 346
  },
  {
    "id": 269,
    "empno": "34569",
    "extension": 345
  },
  {
    "id": 269,
    "empno": "34567",
    "extension": 345
  }
];

const hasDuplicates = (data) => data.length !== data.reduce((a, {empno, extension}) => a.add(`${empno}/${extension}`), new Set).size;

console.log(hasDuplicates(data));

Sign up to request clarification or add additional context in comments.

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.