Categories
JavaScript Answers

How to check for duplicate strings in JavaScript array?

Spread the love

Sometimes, we want to check for duplicate strings in JavaScript array.

In this article, we’ll look at how to check for duplicate strings in JavaScript array.

How to check for duplicate strings in JavaScript array?

To check for duplicate strings in JavaScript array, we can use a set.

For instance, we write

const checkIfDuplicateExists = (arr) => {
  return new Set(arr).size !== arr.length;
};

const arr = ["a", "a", "b", "c"];

console.log(checkIfDuplicateExists(arr));

to define the checkIfDuplicateExists function to check if the arr converted to a set has the same size as the original arr array.

If they have the same size, then there’re no duplicate values in arr since sets can’t have duplicate values but arrays can.

Conclusion

To check for duplicate strings in JavaScript array, we can use a set.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *