Check if an array contains duplicate values

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)}`);

This should work with only one loop:

function checkIfArrayIsUnique(arr) {
    var map = {}, i, size;

    for (i = 0, size = arr.length; i < size; i++){
        if (map[arr[i]]){
            return false;
        }

        map[arr[i]] = true;
    }

    return true;
}

You got the return values the wrong way round:

  • As soon as you find two values that are equal, you can conclude that the array is not unique and return false.

  • At the very end, after you've checked all the pairs, you can return true.

If you do this a lot, and the arrays are large, you might want to investigate the possibility of sorting the array and then only comparing adjacent elements. This will have better asymptotic complexity than your current method.


let arr = [11,22,11,22];

let hasDuplicate = arr.some((val, i) => arr.indexOf(val) !== i);
// hasDuplicate = true

True -> array has duplicates

False -> uniqe array

Tags:

Javascript