0
function f() {
    var FileSize = "250";
    var Ana = new Array;
    Ana["231.78"] = "2.14";
    Ana["234.95"] = "2.11";
    Ana["238.12"] = "2.08";
    Ana["241.30"] = "2.05";
    Ana["244.47"] = "2.02";
    Ana["250.82"] = "1.97";
    Ana["254.00"] = "1.95";
}
f();

I don't know how to write my request. I have a value (250) and need to test the Array until the ID of my Array is less than my "FileSize". In my example, the result should be 1.97.

  • 3
    Note that an array can't have fractional indexes. What you actually have is a zero-length array object with 7 custom properties. – JJJ Dec 18 '13 at 15:03
  • possible duplicate of [Best way to find an item in a JavaScript array?](http://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array) – isherwood Dec 18 '13 at 15:04
  • 2
    How is the result `1.97`? Isn't `250.82 > 250`? – gen_Eric Dec 18 '13 at 15:07

2 Answers2

0

Using simple arrays for your problem might not be the best representation. You could an array of couples :

var Ana = [
   [231.78, 2.14],
   ...
   [254.00, 1.95]
];

This way, you can easily sort your Ana array by ascending order (ascending order regarding the first element of each couple). And you can iterate through your Ana array until you reach your condition, with a simple while or for loop. If you keep Ana sorted, recovering the value is easy and efficient.

Paul D.
  • 2,022
  • 19
  • 19
0

Instead of storing the file size as the key, store the whole information as an object in the array:

var f = function(fileSize){

var ana = [];
ana.push({fileSize: 231.78, randomThing: 2.14});
ana.push({fileSize: 234.95, randomThing: 2.11});
ana.push({fileSize: 234.95, randomThing: 2.08});
ana.push({fileSize: 241.30, randomThing: 2.05});
ana.push({fileSize: 244.47, randomThing: 2.02});
ana.push({fileSize: 250.82, randomThing: 1.97});
ana.push({fileSize: 254.00, randomThing: 1.95});

for(var i=0; i < ana.length; i++){
    if (ana[i].fileSize > fileSize){
        return ana[i].randomThing;
    }
}

return null; //or something more appropriate, this happens when there is no item greater than fileSize  
}
Rui
  • 4,847
  • 3
  • 29
  • 35