A Quick Look at the sort() Array Method in JavaScript

 (╯°□°)╯ .sort()

The Array method sort() is handy for ordering Arrays and Objects.

Simple use

For simple use you can just call sort() on an array.

Let’s say we have an array of numbers that we want sorting from low too high.

const nums = [5, 2, 1, 3, 4]

const numOrder = nums.sort()
// [1,2,3,4,5]

Or is you have an array of strings we want sorting alphabetically.

const phonetics = ["zulu", "foxtrot", "charlie", "alpha"]
const orderPhonetics = phonetics.sort()
// [ 'alpha', 'charlie', 'foxtrot', 'zulu' ]

Sorting Values from Objects

We have an object of dogs:

const dogs = [
  { name: "bob", age: 3 },
  { name: "winston", age: 10 },
  { name: "spike", age: 5 },
]

Let’s say we want to sort the dogs by youngest to oldest:

const ageOrder = dogs.sort((a, b) => {
  if (a.name > b.name) {
     return 1;
  }

  if (a.name < b.name) {
    return -1;
  }
  return 0;
})

/* [ { name: 'bob', age: 3 },
     { name: 'spike', age: 5 },
     { name: 'winston', age: 10 } ]*/

We pass in two arguments to sort() and using a ternerary operator we bubble sort the dogs by age. “Is a.age greater than b.age? If it is +1. If it is lower -1”.

Works the same when sorting alphabetically:

const alphaOrder = dogs.sort((a,b) => {
  if (a.name > b.name) {
    return 1
  }
  if (a.name < b.name) {
    return -1
  }
  return 0
})
/* [ { name: 'bob', age: 3 },
     { name: 'spike', age: 5 },
     { name: 'winston', age: 10 } ] */

Let's connect

Twitter