DEV Community

Discussion on: JavaScript: How to Check if an Array has Duplicate Values

Collapse
 
igorfilippov3 profile image
Ihor Filippov • Edited

Nice technique. But it works only with primitives.
If you do not mind I want to add a bit more info about this topic.
If you need to find duplicates in array of objects, you can do something like this:

function checkForDuplicates(source, keyName) {
  return source.filter((item, index, array) => {
    return array.findIndex(t => t[keyName] === item[keyName]) === index;
  }).length !== source.length
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
johandalabacka profile image
Johan Dahl • Edited

or use almost the same technique as the author:

function checkForDuplicates(array, keyName) {
  return new Set(array.map(item => item[keyName])).size !== array.length
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
igorfilippov3 profile image
Ihor Filippov

Yep. It is cleaner than mine.

Collapse
 
mohammedelseddik profile image
MohammedElseddik

could you please explain this syntax to me and thank you in advance.