Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for duplicate strings in JavaScript array

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.

like image 355
Bengall Avatar asked Mar 11 '18 00:03

Bengall


People also ask

How do you check if there are duplicates in an array JavaScript?

To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.


2 Answers

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
like image 60
Mike Ezzati Avatar answered Sep 28 '22 13:09

Mike Ezzati


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
like image 39
Kamil Naja Avatar answered Sep 28 '22 14:09

Kamil Naja