A logo showing the text blog.marcnuri.com
Español
Home»JavaScript»How to check if an array contains duplicate values in JavaScript?

Recent Posts

  • Fabric8 Kubernetes Client 6.5.0 is now available!
  • Eclipse JKube 1.11 is now available!
  • Fabric8 Kubernetes Client 6.4.1 is now available!
  • I bought an iPad
  • Three years at Red Hat

Categories

  • Front-end
  • Java
  • JavaScript
  • Legacy
  • Operations
  • Personal
  • Pet projects
  • Tools

Archives

  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • December 2019
  • October 2019
  • September 2019
  • July 2019
  • March 2019
  • November 2018
  • July 2018
  • June 2018
  • May 2018
  • April 2018
  • March 2018
  • February 2018
  • December 2017
  • July 2017
  • December 2015
  • November 2015
  • November 2008
  • November 2007
  • September 2007
  • August 2007
  • July 2007
  • June 2007
  • May 2007
  • April 2007
  • March 2007

How to check if an array contains duplicate values in JavaScript?

2022-01-16 in JavaScript tagged JavaScript / Quickie by Marc Nuri | Last updated: 2022-01-22
Versión en Español

Checking if a JavaScript Array contains duplicate values is something that might come in handy. e.g. I sometimes use this in tests to perform some quick verifications.

Considering the following 2 arrays:

const array1 = ['one', 'two', 'three'];
const array2 = ['one', 'two', 'two', 'three'];

The first one, array1, contains no duplicates. However, the second (array2) contains the item 'two' twice.

In an ES2015/ES6 compatible environment, which is very likely if you are using any modern browser or supported Node.js version, it's as easy as running the following snippet:

function containsDuplicates(array) {
  return array.length !== new Set(array).size;
}

References

  • JavaScript | MDN: Set - Remove duplicate elements from the array
  • JavaScript | MDN: Array
Twitter iconFacebook iconLinkedIn iconPinterest iconEmail icon

Post navigation

← Develop cloud native Kubernetes Java applications on Okteto CloudBuild Kubernetes controllers with Fabric8 Kubernetes Client, Quarkus, and JKube →
© 2007 - 2023 Marc Nuri