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);
You could take Array#some
which allowes to exits the iteration if the delta is getting greater than the last delta.
var array = [];array[1513957775] = { lat: 40.671978333333, lng: 14.778661666667, eventcode: 46 };array[1513957845] = { lat: 40.674568332333, lng: 14.568661645667, eventcode: 23 };array[1513957932] = { lat: 41.674568332333, lng: 13.568661645667, eventcode: 133 };var key = 0, search = 1513957855;Object.keys(array).some(function (k) { if (Math.abs(k - search) > Math.abs(key - search)) { return true; } key = k;});console.log(key);
You can use Object.keys(MyEventsArray)
to get an array of the keys (which are strangely expressed as strings); you could then iterate through that and find the closest match.
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};Object.keys(MyEventsArray)
["1513957775", "1513957845", "1513957932"]
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array