arcee123
arcee123

Reputation: 211

How do I get the array value where the key, which is the number, is the next lowest value?

if I have this array in javascript:

array[1] = 'blue';
array[25] = 'green';
array[50] = 'yellow';
array[75] = 'orange';
array[100] = 'red';

and I have:

number = 35

how do I get to:

output = 'green';

Upvotes: 1

Views: 52

Answers (4)

Guffa
Guffa

Reputation: 700342

You can loop through the items in the array, and check which one of the items that are smaller than the number, is closest to the number:

var array = [];

array[1] = 'blue';
array[25] = 'green';
array[50] = 'yellow';
array[75] = 'orange';
array[100] = 'red';

var n = 35, min = null, value;

for (x in array) {
  var diff = n - x;
  if (diff >= 0 && (min == null || diff < min)) {
    min = diff;
    value = array[x];
  }
}

// show result is Stackoverflow snippet
document.write(value);

Upvotes: 0

BatScream
BatScream

Reputation: 19700

Use the method hasOwnProperty() to check if an index is really a property of the array.(For both arrays as well as array-like objects) It is true only if a value has been assigned at that particular index. The first valid index below 35, would contain green.

   var i = 35;
   while(i >= 0){
        if(array.hasOwnProperty(i)){
            console.log(array[i]);
            break;
        }
      i--;
    }

  console.log(i) // gives you 25, which is the next valid index below 35.

Upvotes: 1

wmock
wmock

Reputation: 5492

var firstLessThanX = function (x) {
  var array = [100, 75, 50, 25, 1];
  for (var i = 0; i < array.length; i += 1) {
    if (array[i] < x) {
      return array[i];
    }
  }
  return 'All values greater than or equal to ' + x;
};

array[ firstLessThanX(35) ] // 'green'

Upvotes: 0

alex
alex

Reputation: 490253

If your array is setup like that, including all the empty slots, you could do something like this.

var i = 35;

while ( ! array[--i]) {}

array[i]; // "green"

jsFiddle.

However, if you're trying to show the relationship between those numbers to colours, you should use an object.

Upvotes: 5

Related Questions