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 call the filter method.
For instance, we write
const strArray = ["q", "w", "w", "w", "e", "i", "u", "r"];
const findDuplicates = (arr) =>
arr.filter((item, index) => arr.indexOf(item) !== index);
to define the findDuplicates method.
In it, we call arr.filter with a callback that checks if the first index of item isn’t index.
If they’re different, then the item is a duplicate.
Conclusion
To check for duplicate strings in JavaScript array, we call the filter method.