0

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.

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your answer. I'll try to set i up and create a fiddle. I also need to pass some more information once the right bound is found.
right now it puts out both values 1 and 898, putting them together to 1898
ok now it works. How can i set the limit? for the highest amount? For the last / highest entry in the array?
Well the function assumes at the moment that your input it within the bounds of the array you could do an if statement before the function or somewhere within the function to check the bounds e.g. if (input > bounds[bounds.length -1][1]) {return null;} where null is the value your expect back if it's not within the bounds.
Also as it's a correct answer do you mind marking it as so ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.