Created
November 5, 2014 17:18
-
-
Save jwaltonmedia/cbc017483c4e3414ad6c to your computer and use it in GitHub Desktop.
_.sortedIndex_example.js
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
//assuming 'listItems' is non-alphabetical unordered list (response from server, etc.) | |
var finalArr = []; | |
var idx; | |
_.each(listItems, function(el, i) { | |
// _.sortedIndex magic here... binary compare; | |
// finalArr is passed to _.sortedIndex each time | |
// el - is the current item being acted on in the loop | |
// 'name' is the key in the object whose value will be evaluated when determining index | |
idx = _.sortedIndex(finalArr, el, 'name'); | |
//now add the el to the finalArr at the index returned. | |
finalArr.splice(idx, 0, el); | |
}); | |
return finalArr; //this will be a sorted array | |
//additional documentation: http://underscorejs.org/#sortedIndex | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment