0

my try:

var objects = [
  {"min":"0","max":"50","name":"name1"},
  {"min":"50","max":"100","name":"name2"},
  {"min":"100","max":"150","name":"name3"}
];

var value = 40;

objects.forEach(function(item, i){
    if(Number(item.min) >= value &&  value <= Number(item.max) ){
    console.log("name is ", item.name );
  }
});

getting console as :

name is  name2
name is  name3

but my expectation is name is name2 what is the correct way to get the range value with scenario?

Liam
  • 25,247
  • 27
  • 110
  • 174
3gwebtrain
  • 14,377
  • 24
  • 102
  • 222

4 Answers4

2

Move the value variable so that you're checking if it is greater or equal to the min, otherwise you're checking if the min is greater than or equal to value:-

let objects = [
    {"min":"0","max":"50","name":"name1"},
    {"min":"50","max":"100","name":"name2"},
    {"min":"100","max":"150","name":"name3"}
];

let value = 40;

objects.forEach(function(item, i){
    if (value >= Number(item.min) && value <= Number(item.max)) {
        console.log("name is ", item.name );
    }
});
Joe Keene
  • 1,975
  • 18
  • 27
2

Use Array#find method:

var objects = [
  {"min":"0","max":"50","name":"name1"},
  {"min":"50","max":"100","name":"name2"},
  {"min":"100","max":"150","name":"name3"}
];

var value = 90;

let res = objects.find(obj => Number(obj.min) <= value && value <= Number(obj.max));
console.log(res ? res.name : 'Not found');
alexmac
  • 18,143
  • 7
  • 52
  • 64
1

Here we go, you just had to swap variables:

if(Number(item.min) >= value &&  value <= Number(item.max) ){

if(value >= Number(item.min) &&  value <= Number(item.max) ){

var objects = [
  {"min":"0","max":"50","name":"name1"},
  {"min":"50","max":"100","name":"name2"},
  {"min":"100","max":"150","name":"name3"}
];

var value = 40;

objects.forEach(function(item, i){
    if(value >= Number(item.min) &&  value <= Number(item.max) ){
    console.log("name is ", item.name );
  }
});
Marco Salerno
  • 5,000
  • 2
  • 10
  • 29
0

If your ranges increment by 50, you don't need to iterate at all. We just divide value by 50 and rounded down, giving us the index.

const index = n && Math.floor(n/50) - !(n%50);

Any range from x1 to x50 will be in the lower range, so values like 150 are handled. The 0 value is included in the first range.

var objects = [
  {"min":"0","max":"50","name":"name1"},
  {"min":"50","max":"100","name":"name2"},
  {"min":"100","max":"150","name":"name3"}
];

test(0);
test(10);
test(50);
test(51);
test(100);
test(149);
test(150);
test(151);

function test(n) {
  const index = n && Math.floor(n/50) - !(n%50);
  const res = objects[index];
  console.log("value:", n, ", item:", res ? res.name : 'Not found');
}
llama
  • 2,465
  • 9
  • 9
  • @3gwebtrain: I added a new example that deals with numbers that land on a multiple of 50. – llama Oct 06 '17 at 12:48