0

I have a javascript array of objects:

[
   Object { from="0", to="350", price="25"}, 
   Object { from="351", to="700", price="50"}
   ...
   Object { from="701", to="*", price="75"} // Where * - unlimited value
]

And input value: var total = 100

How can I find a price value?

Example: For total = 100 my price value will be 25.

1
  • 1
    How about a for loop containing an if test with >= and <=? What have you tried? Commented Sep 12, 2013 at 13:13

1 Answer 1

2
var ranges = [
    { from:0, to:350, price:25},
    { from:351, to:700, price:50},
    { from:701, to:"*", price:75}
];    

function isInRange(range, value) {
    return range.from < value && (range.to === '*' || range.to >= value)
}

var value = 100;
var priceFound = false
for (var i = 0; i < ranges.length && !priceFound; i++) {
    var range = ranges[i];
    if (isInRange(range, value)) {
        alert("price: " + range.price);
        priceFound = true
    }
}

I cleaned up your objects definitions because your current version isn't valid javascript.

Sign up to request clarification or add additional context in comments.

Comments

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.