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. }
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.
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.
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)}`);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With