Sorting By Functions in JavaScript

Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in JavaScript.

// We'll use the built-in sort method for arrays in JavaScript
const fruits = ["peach", "banana", "kiwi"];

// We implement a comparison function for string lengths
const lenCmp = (a, b) => a.length - b.length;

// Now we can call sort with this custom comparison function
// to sort fruits by name length
fruits.sort(lenCmp);
console.log(fruits);

// We can use the same technique to sort an array of
// objects that aren't built-in types
class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

const people = [
    new Person("Jax", 37),
    new Person("TJ", 25),
    new Person("Alex", 72)
];

// Sort people by age using the sort method
people.sort((a, b) => a.age - b.age);
console.log(people);

In this JavaScript version:

  1. We use the built-in sort method for arrays, which accepts a comparison function.

  2. The comparison function lenCmp for string lengths is implemented as an arrow function that returns the difference in lengths.

  3. We sort the fruits array using fruits.sort(lenCmp).

  4. For sorting custom objects, we define a Person class instead of a struct.

  5. We sort the people array using an inline arrow function that compares ages.

To run this program, you can save it as a .js file and run it with Node.js:

$ node sorting-by-functions.js
[ 'kiwi', 'peach', 'banana' ]
[
  Person { name: 'TJ', age: 25 },
  Person { name: 'Jax', age: 37 },
  Person { name: 'Alex', age: 72 }
]

Note that JavaScript’s sort method modifies the original array in place, unlike some other languages where sorting returns a new array.