Sort an Array of Objects

Sorting of data is a common problem. Whenever we check something on the internet, be it clothes, flights, shoes, or any other item, the first thing (most of the time) we do is, sort the result. Each website provides sorting based on price, recommendations, popularity, and so on. So how do we sort data?

There is always an array and array comes with the sort function. So can we use this sort function every time we want to sort some data? Will it work when our data is an array of numbers? Will it work when we have some complex data?

Using the sort function which is present with Array prototype is not as easy as it seems. Here is the problem with sort function. Consider we have an array, and for sake of simplicity, let’s say the elements of the array are already sorted.

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Now, let’s call the sort function.

arr.sort();
console.log (arr); // prints [1, 10, 2, 3, 4, 5, 6, 7, 8, 9]

Isn’t it weird? Here is what MDN says about JavaScript sort function:

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

So even if we sort an array whose elements are numbers (for sure), they won’t be sorted based on their value (the position they hold in the number line.

To deal with such scenario, sort function allows a callback function that we can pass as an argument. This callback function, let’s call it the comparator, will actually sort the array as numbers.

arr.sort (function (a, b) {
  if (a > b) return 1; // a must take the lower index in the array
  if (a < b) return -1; // b must take the lower index in then array
  if (a === b) return 0; // no change is required
});

This same function can also be written as (short form),

arr.sort (function (a, b) {
  return a - b;
});
console.log (arr); // prints [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

It may seem a little confusing in the beginning, but it is all right. There are many things in JavaScript which seem weird to a lot many people and they say JavaScript is a weird language. But it’s not. There is some logic behind everything that happens, after all, it’s a scripting language and nothing can happen without logic.

When we talk about sorting an array of objects, we just need to improve the comparator function. Everything else remains the same. Here is the modified sort function which allows sorting of objects based on a key of that object.

/**
 * @description this function sorts an array of objects bases on
 * a key of the object.
 * @params {Array} arr is the array of objects.
 * @params {String} key is the name of field on which objects need to be sorted.
 * @returns {Array} Sorted array.
 */
var sortArrayOfObjects = function (arr, key) {
  // in the following comparator function, a and b will be the objects.
  return arr.sort (function (a, b) {
    var val1 = a[key],
        val2 = b[key];
    // if val1 and val2 are supposed to be numbers, make sure they are parsed.
    // everything else remains the same as before.
    if (val1 > val2) return 1;
    if (val1 < val2) return -1;
    if (val1 === val2) return 0;
  }
};

Read more about sorting on MDN by clicking here.