Felix
Felix

Reputation: 1017

Comparing JSON array with user input and get a value

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

Answers (1)

ShaneQful
ShaneQful

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:

  • Set a variable out which will be our return value to the first bound
  • Loop through the bounds and if the input is lower than the current bound and higher than the previous we set it to be the out value (Note: we skip over the first iteration with idx !== 0 as we have set this as the out value already)
  • By this method we should arrive at the bound which the input is in between and we return this value

Upvotes: 2

Related Questions