javascript check for duplicate before adding to array code example

Example 1: 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"]

Example 2: how to count duplicates in an array javascript

arr.reduce((b,c)=>((b[b.findIndex(d=>d.el===c)]||b[b.push({el:c,count:0})-1]).count++,b),[]);

Tags:

Java Example