Toolroom Tech Blog

Devlopers Digest

JS Snippet 2: Get multiple occurring values from an array

How to get multiple occurring values from an array in JavaScript

See a working Demo here: http://jsfiddle.net/liboswar/moc4y35s/

/**
 * Get multiple occurring values from an array.
 * @param {Array} arr - The Array to check for duplicates
 * @param {Function} [parseFunction] - Optional function that is used to parse each value. I.e. parseInt
 */
function multiples(arr, parseFunction) {
    var i,
    len=arr.length,
    out=[],
    obj={};

//Count occurrence of each value
    for (i=0;i<len;i++) {
        key = arr[i];
        obj[key]=obj[key]===undefined?1:(obj[key]+1);
    }


    //Now push all items with multiple occurrence into result
    for (i in obj) {
        if(obj[i] > 1) {
            if(parseFunction) {
                i = parseFunction.call(null, i);
            }
            out.push(i);
        }
    }
    return out;
}


//returns ["4", "5", "7"]
console.log(multiples([1,2,3,4,4,5,5,6,7,7,7,7,7,8]));

//returns [4, 5, 7]
console.log(multiples([1,2,3,4,4,5,5,6,7,7,7,7,7,8], parseInt));