check if an array contains duplicate values code example

Example 1: javascript check if array has duplicates

function hasDuplicates(array) {
    return (new Set(array)).size !== array.length;
}

Example 2: javascript get duplicates in array

function getDuplicateArrayElements(arr){
    var sorted_arr = arr.slice().sort();
    var results = [];
    for (var i = 0; i < sorted_arr.length - 1; i++) {
        if (sorted_arr[i + 1] === sorted_arr[i]) {
            results.push(sorted_arr[i]);
        }
    }
    return results;
}

var colors = ["red","orange","blue","green","red","blue"];
var duplicateColors= getDuplicateArrayElements(colors);//["blue", "red"]

Tags:

Java Example