DEV Community

Cover image for Wanna sort() things out in JavaScript ?
Zakaria Elk
Zakaria Elk

Posted on

Wanna sort() things out in JavaScript ?

We all have our life priorities, sometimes we stick to them and others we let loose. JavaScript doesn't, especially if you use the sort() method properly.

In a nutshell, the sort() method sorts the elements of an array in place and returns the sorted array.

How does it really work?

Let's first have a quick look at sort() basic syntax (from mdn)

Syntax

arr.sort([compareFunction])

The compareFunction is optional and can be set if we want to define a the sort order. If compareFunction is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order.

If compareFunction is supplied, all non-undefined array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

  • If compareFunction(a, b) returns less than 0, sort a to an index lower than b (i.e. a comes first).
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) returns greater than 0, sort b to an index lower than a (i.e. b comes first).
function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

Not convinced? 🤔 Let's try sorting these numbers

const numbers = [1, 2, 100, 3, 200, 400, 155];
const numbersSorted = numbers.sort(function(firstItem, secondItem) {
    if(firstItem > secondItem) {
        return 1;
    } else if (firstItem < secondItem) {
        return -1;
    } else {
        return 0;
    }
})

console.log(numbersSorted); // [1, 2, 3, 100, 155, 200, 400]

We can shorten this function to

const numbersSorted = numbers.sort((firstItem, secondItem) => firstItem - secondItem);
console.log(numbersSorted); // [1, 2, 3, 100, 155, 200, 400]

This time, let's not set a compare function and rely on the default one as mentioned earlier. Let's sort the following toppings array alphabetically

const toppings = ["Mushy Boi", "Chili", "Pickles", "Avocado", "Onions", "Cheese", "Chiles","Hot Sauce", "Bacon", "Lettuce", "Tomatoes", "Mushy Boi", "Eggs"]
console.log(toppings.sort()); //["Avocado", "Bacon", "Cheese", "Chiles", "Chili", "Eggs", "Hot Sauce", "Lettuce", "Mushy Boi", "Onions", "Pickles", "Tomatoes

Let's push it a little more and sort the prices

const productsSortedByPrice = Object.entries(prices).sort(function (a, b) {
  const aPrice = a[1];
  const bPrice = b[1];
  return aPrice - bPrice;
});
console.table(Object.fromEntries(productsSortedByPrice));
  1. We use the Object.entries to get everything as we need to display both keys and values.
  2. We call our sort and set a function with (a, b) which will hold the first and second item of each success pairs.
  3. We set 2 variables that will hold the values of the entries. In our case the price.
  4. We return the difference which will set the order of prices by returning (-1, 1 or 0)
  5. We log the result by converting our result array into an object using Object.fromEntries, and we return our function result inside of it. Here we're using console.table for a better display of the result.

I hope you learned a thing or 2 from the above post. If you liked it, hit any of those nicely designed buttons, and let's connect! 🚀

Top comments (0)