DEV Community

David Bell
David Bell

Posted on • Originally published at davidbell.space

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

 (╯°□°) .sort()
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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' ]
Enter fullscreen mode Exit fullscreen mode

Sorting Values from Objects

We have an object of dogs:

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

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 } ]*/
Enter fullscreen mode Exit fullscreen mode

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 } ] */
Enter fullscreen mode Exit fullscreen mode

Let's connect

Twitter

Top comments (0)