LeBlaireau LeBlaireau - 7 months ago 45
Javascript Question

Javascript lookup table

I have an object which holds my data.

DataSoccer: [{ 0: '0.00', 1: '10.4', 2:'100.5', 3:'15.3', 4:'11.2', 5:'15.9'}]


when the key values are whole this is simple.

DataSoccer[0][3] //returns 10.4

The problem is the indexes are now not whole

DataSoccer: [{ 0: '0.00', 1.30: '10.4', 2.40:'100.5', 3.40:'15.3', 4.5:'11.2', 5:'15.9'}]


so I get a user input, say 2.30 and that should return 10.4 (the second index)

At the moment I have an if statement

if (value == 0 {
return 0.00
}
else if (value <= 1.30) {
return 10.4
}

else if (value <= 2.40) {
return 100.5
}


As you can imagine this lookup functionality using an if-else can get pretty cumbersome and was wondering if there was a better way?

Answer

try this

var DataSoccer =  [{ 0: '0.00', 1.30: '10.4', 2.40:'100.5', 3.40:'15.3', 4.5:'11.2', 5:'15.9'}];

//sort all the keys in DataSoccer[0]
var sortedKeys = Object.keys(DataSoccer[0]).sort(function(a,b){ return parseFloat(a) - parseFloat(b) }); 

//get value lesser than 2.3 which is 1.3
var smallerKey = sortedKeys.filter(function(val){ return val < 2.3}).pop(); 

//get next value which is 2.4 after 1.3
var actualKey = sortedKeys[sortedKeys.indexOf(smallerKey) + 1]; 

//alerting the value at 2.4
alert("value is " + DataSoccer[0][actualKey] ); //access value ar 2.4