Checking for duplicate strings in JavaScript array
Solution 1:
The findDuplicates
function (below) compares index of all items in array with index of first occurrence of same item. If indexes are not same returns it as duplicate.
let strArray = [ "q", "w", "w", "w", "e", "i", "u", "r"];
let findDuplicates = arr => arr.filter((item, index) => arr.indexOf(item) != index)
console.log(findDuplicates(strArray)) // All duplicates
console.log([...new Set(findDuplicates(strArray))]) // Unique duplicates
Solution 2:
Using ES6 features
- Because each value in the Set has to be unique, the value equality will be checked.
function checkIfDuplicateExists(arr) {
return new Set(arr).size !== arr.length
}
var arr = ["a", "a", "b", "c"];
var arr1 = ["a", "b", "c"];
console.log(checkIfDuplicateExists(arr)); // true
console.log(checkIfDuplicateExists(arr1)); // false
Solution 3:
var strArray = [ "q", "w", "w", "e", "i", "u", "r", "q"];
var alreadySeen = [];
strArray.forEach(function(str) {
if (alreadySeen[str])
alert(str);
else
alreadySeen[str] = true;
});
I added another duplicate in there from your original just to show it would find a non-consecutive duplicate.
Updated version with arrow function:
const strArray = [ "q", "w", "w", "e", "i", "u", "r", "q"];
const alreadySeen = [];
strArray.forEach(str => alreadySeen[str] ? alert(str) : alreadySeen[str] = true);