Created
December 2, 2011 15:40
-
Star
(109)
You must be signed in to star a gist -
Fork
(22)
You must be signed in to fork a gist
-
-
Save ecarter/1423674 to your computer and use it in GitHub Desktop.
Revisions
-
ecarter created this gist
Dec 2, 2011 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,41 @@ /** * Sort array of objects based on another array */ function mapOrder (array, order, key) { array.sort( function (a, b) { var A = a[key], B = b[key]; if (order.indexOf(A) > order.indexOf(B)) { return 1; } else { return -1; } }); return array; }; /** * Example: */ var item_array, item_order, ordered_array; item_array = [ { id: 2, label: 'Two' } , { id: 3, label: 'Three' } , { id: 5, label: 'Five' } , { id: 4, label: 'Four' } , { id: 1, label: 'One'} ]; item_order = [1,2,3,4,5]; ordered_array = mapOrder(item_array, item_order, 'id'); console.log('Ordered:', JSON.stringify(ordered_array));