richie - 1 year ago 61
Javascript Question

# Determine the bucket to which a number belongs to

How do you determine the bucket to which a number belongs to? For ex, lets say we have buckets 0 - 20, 21 - 50, 51 - 80, 81 - 100 or the equivalent grades as 'Poor', 'Average', 'Good', 'Great'. Is there an efficient way using jquery/lodash/d3/underscore to find out that '45' belongs to the '21 - 50' bucket or is 'Average'?

Edit: Is this the best way to do it? In terms of speed, minimal code etc.

Here's what I have with a lot of help;

``````// Set up your data
var range = [[0, 20], [21, 50], [51, 80], [81, 100]]
var number = 45

range.find(function(val) { return val[1] >= number })
// Returns [21, 50]

range.findIndex(function(val) { return val[1] >= number })
// Returns 1
``````

You can use an array of objects with properties set to from `"Poor"` to `"Great"` corresponding to the range of numbers set as value of the property, `Array.prototype.filter()`

``````var range = [{
Poor: [0, 20]
}, {
Average: [21, 50]
}, {
Good: [51, 80]
}, {
Great: [81, 100]
}];

var number = 45;

var res = range.filter(function(el) {
var key = el[Object.keys(el)];
return number > key[0] && number < key[1]
});

console.log(Object.keys(res[0])[0])``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download