Find closest array index Find closest array index json json

Find closest array index


There is no difference between MyEventsArray[1513957775] and MyEventsArray['1513957775']. Deep down, array indexes are just property names, and property names are strings.

Regarding the question of whether these sparse indices will lead to millions of empty cells being allocated, no, that won't happen. Sparse arrays only store what you put in them, not empty space.

If you want to find a key quickly, you can obtain an array of the keys, sort them, and then find the one you want:

var MyEventsArray=[];MyEventsArray[1513957775]={lat:40.671978333333, lng:14.778661666667, eventcode:46};MyEventsArray[1513957845]={lat:40.674568332333, lng:14.568661645667, eventcode:23};MyEventsArray[1513957932]={lat:41.674568332333, lng:13.568661645667, eventcode:133};var target = 1513957855;var closest= Object.keys(MyEventsArray)                   .map(k => ({ k, delta: Math.abs(target - k) }))                     .sort((a, b) => a.delta - b.delta)[0].k;console.log(closest);