-1

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
  • 27,717
  • 28
  • 128
  • 190
3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

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
  • 2,175
  • 21
  • 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
  • 19,087
  • 7
  • 58
  • 69
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,131
  • 2
  • 12
  • 32
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,535
  • 12
  • 11
  • @3gwebtrain: I added a new example that deals with numbers that land on a multiple of 50. – llama Oct 06 '17 at 12:48