Created
August 22, 2012 07:49
-
-
Save tschueller/3423559 to your computer and use it in GitHub Desktop.
Sort a javascript array by the order of an other array
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 characters
var arrayToSort = ["z", "a", "c", "f", "e", "d" ]; | |
var sortOrder = ["a", "b", "c", "d", "e"]; | |
arrayToSort.sort(function(a,b) { | |
var sa = sortOrder.indexOf(a); | |
var sb = sortOrder.indexOf(b); | |
if (sa == -1) return 1; | |
if (sb == -1) return -1; | |
return sa < sb ? -1 : 1; | |
}); | |
window.console.log(arrayToSort); | |
// Result: ["a", "c", "d", "e", "f", "z"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment