简体   繁体   中英

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.

Essentially you need to loop through each of the bounds to find where the persons income is eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM