I have JS array with strings, for example:
var strArray = [ "q", "w", "w", "e", "i", "u", "r"];
I need to compare for duplicate strings inside array, and if duplicate string exists, there should be alert box pointing to that string.
I was trying to compare it with for
loop, but I don’t know how to write code so that array checks its own strings for duplicates, without already pre-determined string to compare.
Advertisement
Answer
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