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];
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With