Reputation: 1017
I am building some kind of calculator where the user can input his income and then the function iterates on a JSON array to find the according number. It should be something like:
if (z >= x && z <= y)
Where z is the user input and x and y are the limits on both sides.
Here is the JSON array (only 3 out 100):
[["0",0],["1",898],["2",12654],["3",15753]]
I don't know how to write this function. I could do it using 100 ifs and elseifs though. But I am pretty sure there is a nicer way.
Upvotes: 0
Views: 146
Reputation: 2236
Essentially you need to loop through each of the bounds to find where the persons income is e.g.
function getIncomeBound(input) {
//Note: this is not the best way to store this data but that's another issue
var bounds = [["0",0],["1",898],["2",12654],["3",15753]];
var out = bounds[0];
bounds.forEach(function (el, idx) {
out = (idx !== 0 && input <= el[1] && input > bounds[idx - 1][1] ? el : out);
});
return out;
}
Explanation:
idx !== 0
as we have set this as the out value already)Upvotes: 2