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

JS Snippet 1: Remove duplicate values from an array

How to remove duplicate values from an Array in JavaScript

See a working example here: http://jsfiddle.net/liboswar/4bq805oL/

function unique(arr) {
    var i,
      len=arr.length,
      out=[],
      obj={};
   
    //Store each value as key/value pair in a new object
    for (i=0;i<len;i++) {
        obj[arr[i]]=arr[i];
    }
   
    //Now push the object into the result array
    for (i in obj) {
        out.push(obj[i]);
    }
    return out;
}

console.log(multiples([1,2,3,4,4,5,5,'Hello World','Hello World',6,7,7,7,7,7,8], parseInt));
//result: [1, 2, 3, 4, 5, 6, 7, 8, "Hello World"]