Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnderscoreJS group by numerical intervals for histogram

Is there a way to group a list of numbers into numerical intervals with underscore?

// Input:
var arr = [0,1,2,8];
var interval = 3;

// Output:
// There are 3 numbers from 0 to <3
// There are 0 numbers from 3 to <6
// There is 1 number from 6 to <9 
// Returns [3, 0, 1]

I notice some solutions don't test larger values. Try a second test case:

var arr = [110,113,116,119];
like image 916
Jack Wade Avatar asked Nov 09 '22 03:11

Jack Wade


1 Answers

In plain Javascript, you could just divide the number by the interval and use the integer part for grouping.

With an array and missing intervals.

function getHistogram(array, interval) {
    var bin,
        result = [];

    array.forEach(function (a) {
        var key = Math.floor(a / interval);
        if (!bin) {
            bin = [key, key];
            result[0] = 0;
        }
        while (key < bin[0]) {
            --bin[0];
            result.unshift(0);
        }
        while (key > bin[1]) {
            ++bin[1];
            result.push(0);
        }
        ++result[key - bin[0]];
    });
    return result;
}

console.log(getHistogram([0, 1, 2, 8], 3));
console.log(getHistogram([110, 113, 116, 119], 3));
console.log(getHistogram([15, 10, 26], 3));
.as-console-wrapper { max-height: 100% !important; top: 0; }

With an object and missing intervals.

function getHistogram(array, interval) {
    var bin,
        result = {};

    array.forEach(function (a) {
        var key = Math.floor(a / interval);
        if (!bin) {
            bin = [key, key];
            result[key] = 0;
        }
        while (key < bin[0]) {
            result[--bin[0]] = 0;
        }
        while (key > bin[1]) {
            result[++bin[1]] = 0;
        }
        ++result[key];
    });
    return result;
}

console.log(getHistogram([0, 1, 2, 8], 3));
console.log(getHistogram([110, 113, 116, 119], 3));
console.log(getHistogram([15, 10, 26], 3));
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 60
Nina Scholz Avatar answered Nov 15 '22 07:11

Nina Scholz