Skip to content Skip to sidebar Skip to footer

Counting The Number Of Times Each Value In The Array Appears In That Array (javascript)

I've got a question as to how I should go about performing some math over an array. My apologies if this is a basic question, javascript is not my strongest language and I'm a med

Solution 1:

var arr = [1, 1, 0.7, 0.3, 1, 0.8, 1, 0.8, 0.7, 1];
document.write(compute(arr));
 
function compute(arr){
    freq = {};
    for(var i=0; i<arr.length; i++){
        freq[arr[i]] = (freq[arr[i]] || 0) + 1;
    }
    
    var sum = 0;
    for(var i in freq){
        sum += freq[i]*(freq[i]-1)*(freq[i]*2-5);
    }
    return sum;
}

Solution 2:

function foo(arr) {
    var a = [], b = [], prev;
    arr.sort();
    for( var i = 0; i < arr.length; i++ ){
        if ( arr[i] !== prev ) {
            a.push(arr[i]);
            b.push(1);
        } else {
            b[b.length-1]++;
        }
        prev = arr[i];
    }
    return [a, b];
}

var arr = [1, 1, 0.7, 0.3, 1, 0.8, 1, 0.8, 0.7, 1];
var result = foo(arr);
// result[0] contain unique array elements and result[1] contain number of occurrences of those elements
for(var i = 0; i < result[0].length; i++){
    document.write(result[0][i] + " : " + result[1][i] + "<br>");
}

Post a Comment for "Counting The Number Of Times Each Value In The Array Appears In That Array (javascript)"