0

Hi I am trying to check a value that is matching some range in an dynamic array.I have a amount for example say 3555, I have a array [1000,2000,999999]. Normally we can use if statement to check for dynamic range like,

if(3555<100)
{
    //do something
}
elseif(3555<2000)
{
    //do something
}
elseif(3555<999999)
{
    //do something
}

Condition that I need to implement is that static amount(3555) is greater that some value and less than some value,To be more specific like Amount < 1000 >2000 Now I have a dynamic array to feed as input.How could I check for condition that is true and get the array index? Can someone help me?

5 Answers 5

2

No need of jQuery for something like that, a simple way to get what you want is to run you test for each couple value of the range array, and if something match to return the index.

function test(number, ranges) {
  for (var i = 0; i < ranges.length; ++i) {
    if (number < ranges[i]) {
      return i;
    }
  }
}


var ranges = [1000, 2000, 999999];

console.log(test(3555, ranges));

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

2 Comments

index that should match is the last one 999999? How to do that?@user3
return i+1 instead of i, I assumed you wanted the index of the lower bound ;) @Anu
1

Maybe this one?

getIndex = function(array, amount) {
for(var i in array.sort()) {
    if(array[i] > amount) {
      return i;
    }
  }
  return -1;
};

This will return the index from the number greater than amount

Fiddle: https://jsfiddle.net/diegopolido/6wuutsk6/

2 Comments

if 3555 is the input amount it should satisfy 99999. because the value is 3000 and above. Can you please help me?@Diego Polido Santana
This function will return 2 (the index of 999999). Look at the fiddle
1

You could iterate the array like so (this would return the first index where num is greater than the value in the array or -1 if none is found)

function amount(array, num) {
    array.forEach(function(val, index){
        if (val < num) {
            return index;
        }
    });
    return -1;
}

Comments

0

You may use filter function:

var arr = [100, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 999999];
var min = 1000;
var max = 4010;

var resultingArray = arr.filter(function(val, index, ar) {
  return val < max && val > min;
});

document.write('Result is: ' + resultingArray);

Comments

0
var theArray = [100,300,800,1000,1300];
var goal = 400;
var nearest= null;
$.each(theArray, function(){
    if (nearest == null || Math.abs(this - goal) < Math.abs(nearest - goal){
        nearest = this;
    }
});

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.