Skip to content

Instantly share code, notes, and snippets.

@jwaltonmedia
Created November 5, 2014 17:18
Show Gist options
  • Save jwaltonmedia/cbc017483c4e3414ad6c to your computer and use it in GitHub Desktop.
Save jwaltonmedia/cbc017483c4e3414ad6c to your computer and use it in GitHub Desktop.
_.sortedIndex_example.js
//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