Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an array contains duplicate values

Tags:

javascript

I wanted to write a javascript function which checks if array contains duplicate values or not.

I have written the following code but its giving answer as "true" always.

Can anybody please tell me what am I missing.

function checkIfArrayIsUnique(myArray)      {         for (var i = 0; i < myArray.length; i++)          {             for (var j = 0; j < myArray.length; j++)              {                 if (i != j)                  {                     if (myArray[i] == myArray[j])                      {                         return true; // means there are duplicate values                     }                 }             }         }         return false; // means there are no duplicate values.     } 
like image 841
milan m Avatar asked Oct 29 '13 10:10

milan m


People also ask

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

One of the most common ways to find duplicates is by using the brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for academic purposes.

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

Using Set A simple and elegant solution is to construct a set from the array which retains only distinct elements. Then simply compare the set's size against the array's length. If both are not the same, then we can say that the array contains duplicates. This works in linear time and space.


1 Answers

An easy solution, if you've got ES6, uses Set:

function checkIfArrayIsUnique(myArray) {    return myArray.length === new Set(myArray).size;  }    let uniqueArray = [1, 2, 3, 4, 5];  console.log(`${uniqueArray} is unique : ${checkIfArrayIsUnique(uniqueArray)}`);    let nonUniqueArray = [1, 1, 2, 3, 4, 5];  console.log(`${nonUniqueArray} is unique : ${checkIfArrayIsUnique(nonUniqueArray)}`);
like image 107
natetitterton Avatar answered Sep 23 '22 15:09

natetitterton