Skip to content

Instantly share code, notes, and snippets.

@ecoleman
Created May 9, 2012 17:25
Show Gist options
  • Save ecoleman/2646936 to your computer and use it in GitHub Desktop.
Save ecoleman/2646936 to your computer and use it in GitHub Desktop.
Sort JS Array based on another arrays positions
var positions = ['id1', 'id3', 'id2'];
var data = [{'id' : 'id1'}, {'id': 'id2'}, {'id': 'id3'}];
var sorted = data.sort(function(a, b) {
var a_pos = positions.indexOf(a.id);
var b_pos = positions.indexOf(b.id);
if (a_pos === b_pos)
return 0;
return (a_pos > b_pos) ? 1 : -1;
});
console.log("sorted", sorted);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment