Skip to content

Instantly share code, notes, and snippets.

@taywils
Created April 13, 2017 07:49
Show Gist options
  • Save taywils/caea70b5868059b88ca508236b226a8e to your computer and use it in GitHub Desktop.
Save taywils/caea70b5868059b88ca508236b226a8e to your computer and use it in GitHub Desktop.
Sort a JSON API response array of objects by a unique key
// Example data from a JSON API that returns an array where each object
// has a unique ID. However the API returns the data in a random order.
var myObjects = [
{
data: 'APPL',
id: 33
},
{
data: 'MSFT',
id: 241
},
{
data: 'SNAP',
id: 1543
}
];
// Array of ids which represent the order we want
var order = [241, 33, 1543];
// Create a meta-object dictionary with mappings between uniqueID -> data
var sortMap = {};
for(o in myObjects) {
obj = myObjects[o];
sortMap[parseInt(obj.id)] = obj;
}
console.log(sortMap);
// Create a new array that looks only N times where N is the number of objects
// in your desired order array.
var orderedObjects = [];
for(var i = 0; i < order.length; ++i) {
orderedObjects.push(sortMap[order[i]]);
}
console.log(orderedObjects);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment