# Underscore JS sortBy Function

Click to share! ⬇️

This Underscore JS tutorial will focus on the Underscore sortBy function, which works with both JavaScript objects and JavaScript arrays. Like the other tutorials that offer code examples we can run, so too will we offer several examples of the `sortBy()` function here. We’ll look at sorting an integer array, sorting string arrays, sorting by the property name of an array of objects, as well as setting up custom sort criteria. Let’s have a look at the Underscore `sortBy()` function now.

### sortBy Integer Array Example

This first example has a simple integer array set up with the values of 1 through 10 assigned to the values variable. In JavaScript, arrays already have a built in sort function, so why the need for an Underscore sortBy function? Well, the sortBy function has just a bit more granularity associated with it. This first example makes use of an `oddSorter` function which we can pass as the second argument to the `sortBy()` function to customize how sorting happens. What we do in this case is to sort the odd numbers first, followed by the even numbers. The `sortBy()` function offers just a bit more control over how you sort.

``````var values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var oddSorter = function (value) {
return value % 2 === 0;
};

var sortedValues = _.sortBy(values, oddSorter);

log('Sort odd numbers first:', '#sortbyexampleoneunderscore');
log(sortedValues, '#sortbyexampleoneunderscore');
``````

### sortBy String Array Example

Example two of the `sortBy()` function will demonstrate sorting an array of strings. The default behavior is to simply sort an array of strings alphabetically. In this case, we want to change that default behavior. To do so, we can again set up a custom iterator function passed as the second argument to `sortBy()` to do this for us. What we do here is to set up this custom criteria to sort by the length of each string in the array. This is found in the `lengthSorter` variable which holds the function to do this. When we run the code, we can see how this works. It’s kind of cool how in sorting this way, the shortest length comes first, followed by longer lengths. We almost create a string pyramid of sorts like this!

``````var values = ['Underscore', 'jQuery', 'Angular', 'React', 'Backbone'];

var lengthSorter = function (value) {
return value.length;
};

var sortedValues = _.sortBy(values, lengthSorter);

log('Sort by length of name:', '#sortbyexampletwounderscore');
log(sortedValues, '#sortbyexampletwounderscore');
``````

### sortBy Object Array Property Name Example

The third example of using the `sortBy()` function deals with sorting an array of objects based on a key of our choosing. So here we have an array of six objects. Each object represents an electric bicycle. We have models by Izip, Anferro, ProdecoTech, Haibike, Benelli, and BH Easy Motion. We would like to sort by the brand of each bike. Notice that the brand is the first key of each ebike object. This is pretty easy. All we do is pass in the array of ebike objects as the first parameter to `sortBy()` and the key we would like to sort by as the second parameter. In this case, that is `brand`. If we run the code, we can see the bikes are indeed sorted by brand in alphabetical order.

``````var ebikes = [
{brand: 'ProdecoTech', country: 'United States'},
{brand: 'Bh Easy Motion', country: 'Spain'},
{brand: 'Benelli', country: 'Italy'},
{brand: 'Haibike', country: 'Germany'},
{brand: 'Anferro', country: 'Mexico'},
{brand: 'Izip', country: 'United States'}
];

var logBike = function (bike) {
log(bike.brand, '#sortbyexamplethreeunderscore');
};

var sortedBikes = _.sortBy(ebikes, 'brand');

log('Bikes sorted by brand:', '#sortbyexamplethreeunderscore');
_.each(sortedBikes, logBike);
``````

### sortBy Object Array Sort Criteria Example

The final example of the sortBy() function will make use of a few more tricks for more complex sorting. In looking at the data we have to work with, we have the ebike’s array, which has ebike objects in here for ProdecoTech, Bh Easy Motion, Benelli, Haibike, Anferro, and Izip. There is also an additional array in `bikesSortOrder` which holds, you guessed it, the sort order based on the index of the array. In looking at the `sortCriteria` function we can see that it’s returning the value from `bikeSortOrder` based off of the index that’s being passed into it. Finally, when we call the `sortBy()` function, we pass in the ebikes array of objects and the sortCriteria function. Running the code shows us that this does work. We actually set the sort order in reverse so to speak by setting up the `bikesSortOrder` array in descending index values. We could put those index values in any order we want to apply the custom sort if we like too.

``````var ebikes = [
{brand: 'ProdecoTech', country: 'United States'},
{brand: 'Bh Easy Motion', country: 'Spain'},
{brand: 'Benelli', country: 'Italy'},
{brand: 'Haibike', country: 'Germany'},
{brand: 'Anferro', country: 'Mexico'},
{brand: 'Izip', country: 'United States'}
];

var bikesSortOrder = [5, 4, 3, 2, 1, 0];

var sortCriteria = function (bike, index, list) {
return bikesSortOrder[index];
};

var logBike = function (bike) {
log(bike.brand, '#sortbyexamplefourunderscore');
};

var sortedBikes = _.sortBy(ebikes, sortCriteria);

log('Bikes sorted by brand:', '#sortbyexamplefourunderscore');
_.each(sortedBikes, logBike);
``````

### Underscore JS sortBy Function Summary

This wraps up another fun tutorial for using the sortBy function in the Underscore JavaScript library. We can see the power and flexibility we have with sortBy when we need to set custom sort criteria to get the results we want whether working with integer arrays, strings, arrays of objects, or various other types of data.

Click to share! ⬇️