Alter Ego Alter Ego - 28 days ago 10
jQuery Question

Get ID back after array sort?

How can I get my giving ID back after sorting the array?

var distance = [];


I loop through a JSON file and add the ID and the response (response is the distace between the current user location and the store location) to the array distance:
distance[item.properties.Nid] = response;
.

After each added new distance to the array I sort the array again:

sort_stores = function(stores){
stores = stores.filter(function(item){
return item !== undefined;
});

stores.sort(function(a, b){
return a - b;
});

console.log(stores);
};


But how can I get my ID
distance[item.properties.Nid]
back? When I log
stores
to my console, only the response is logging..

Answer

Organise your data differently, so that your data has both the ID and the distance in one object.

So, store as follows:

distance.push( { Nid: item.properties.Nid, distance: response });

And sort with this function:

sort_stores = function(stores){
    // NB: first step (filter out undefined) is not needed anymore
    stores.sort(function(a, b){
        return a.distance - b.distance; // add distance property
    });

    console.log(stores);
};