30 Days Of JavaScript

Day 10: Higher Order Functions Part 1

Lesson 2: sort

Look at this array:

1const ages = [3, 7, 33, 23, 68, 7, 44];

It's a bit of a disorganized mess, let's fix that with the sort function.

This is a higher order array function that, like forEach takes a function that it uses to determine how to sort the items in the array. What's great about this function is you don't need to worry about how it's doing the sorting under the hood, you just provide a function that returns either a positive number, 0 or a negative number depending on how the items compare.

To do this we need a function that takes two arguments (a, b) and applies some calculation to them to produce either a positive number, 0 or a negative number. For a simple number sorter this would do the trick:

1(a, b) => {
2  if (a < b) {
3    return -1;
4  }
5  if (a > b) {
6    return 1;
7  }
8  return 0;
9};

Your JavaScript should be good enough by this point to under stand that code, and that a short hand for this when a and b are numbers would be:

1(a, b) => {
2  return a - b;
3};

Or if we want to get REALLY short hand then:

1(a, b) => a - b;

Let's see this in action:

Sort returns a new array AND sorts the existing array in place. So that's something to be aware of.

This sorts the array in ascending order. If the result of a - b is negative then a gets put before b in the array, if the result is positive then b gets put before a in the array. If the result is 0 then the items are left as they are (hence the 7s land up next to each other in the above playground)

With that in mind can you modify the playground above to sort descending?

I'll give you a hint, you just need to swap a couple of things around.

Sorting more than numbers

You can sort anything in an array you like, so long as you can write code that takes a and b and returns a number that is positive, negative or just 0 then you can sort it.

Sort strings by length

1const strings = ["Simon", "David", "Sara", "Rita"];
2
3const sortedStrings = strings.sort((a, b) => a.length - b.length);
4console.log(sortedStrings);

Sort objects by a property

1const cars = [
2  { model: "Vantage", topSpeed: 230 },
3  { model: "Juke", topSpeed: 130 },
4  { model: "5 Series", topSpeed: 190 },
5];
6
7const sortedCars = cars.sort((a, b) => a.topSpeed - b.topSpeed);
8console.log(sortedCars);

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co