DEV Community

Cover image for Understanding Javascript's Array Sort
Anthony DiPietrantonio
Anthony DiPietrantonio

Posted on

Understanding Javascript's Array Sort

When working with data it is a good idea to have the data sorted in some type of meaningful way. Luckily for Javascript developers, the language comes with a built in sort method that can be used on arrays. Great — so why are we here? While the sort method is great on standard strings, there are few gotchas that may trip up some developers. The goal of this article is to cover some of the common gotchas and to cover the basics of this array method.

https://media.giphy.com/media/l4EoT59vRYdTSi6vS/giphy.gif

How The Method Works

By default, the sort method will return a sorted array in ascending order based on their UTC-16 code unit values. This is done by converting each element of the array into a string.

Note: This does not return a copy, it will sort the original array.

Here it is in action on an array of lowercased elements

let colors = ["orange","green","blue","red"]
console.log(colors.sort()) // ["blue", "green", "orange", "red"]
Enter fullscreen mode Exit fullscreen mode

https://media.giphy.com/media/l1KVaJ2P5v9YrhrOg/giphy.gif

Pretty straight forward so far, but since the default behavior of sort is to convert the elements to strings, then sort it in ascending order based on their UTC-16 code unit values, we'll run into some issues if our elements change even in the slightest way.

// element(s) is/are capitalized
let colors = ["orange","Green","blue","red"]
console.log(colors.sort()) // ["Green", "blue", "orange", "red"]

let numbers = [10,60,6,1,5,55,14]
console.log(numbers.sort()) // [1, 10, 14, 5, 55, 6, 60]

let people = [{name: "mark", age: 22},{name: "jill", age: 10},{name: "anthony", age: 16}]
console.log(people.sort())
// [{ name: "mark", age: 10 },{ name: "jill", age: 16 },{ name: "anthony", age: 22 }]
Enter fullscreen mode Exit fullscreen mode

https://media.giphy.com/media/FbhvYtCgfa170yRpV9/giphy.gif

What I haven't mentioned yet is that the sort method takes in an optional parameter, a compare function, that you can pass to it to define the sort order of the array, which will prevent the method from converting all of the elements to strings, and then sorting those converted "strings".

How the Optional compareFunction Parameter Works

When a compareFunction is given, the elements are sorted based on what is returned by the compareFunction. It goes like this — if...:

  • compareFunction(a, b) returns less than 0: the index of a will be set lower than b
  • compareFunction(a, b) returns 0: nothing changes, already sorted
  • compareFunction(a, b) returns greater than 0: the index of a will be set higher than b

The general idea of the compareFunction is this:


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

So at this point we know that a regular sort without a compareFunction will do just fine, but what about for situations where we have numbers or objects?

In comes the compareFunction....

Examples with numbers :

function sortByLength(a, b) {
    return a.length - b.length
}

function compareNumbers(a,b){
    return a - b
}

let strings = ["hello","hi","hey"]
console.log(strings.sort(sortByLength)) // ["hi","hey","hello"]

let numbers = [10,60,6,1,5,55,14]
console.log(numbers.sort(compareNumbers)) // [1, 5, 6, 10, 14, 55, 60]

Enter fullscreen mode Exit fullscreen mode

Example with objects:

function sortByName(a,b){
    // ignore upper/lowercase by setting all elements to lowercase
    let nameA = a.name.toLowerCase()
  let nameB = b.name.toLowerCase()
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }
  return 0;
}

function sortByAge(a,b){
    return a.age - b.age
}

let people = [{name: "mark", age: 22},{name: "JILL", age: 10},{name: "anthony", age: 16}]

console.log(people.sort(sortByName))
// [{name: "anthony", age: 16}, {name: "JILL", age: 10}, {name: "mark", age: 22}]

console.log(people.sort(sortByAge))
// // [{name: "JILL", age: 10}, {name: "anthony", age: 16}, {name: "mark", age: 22}]
Enter fullscreen mode Exit fullscreen mode

Note: if you copy and paste this code, you'll have to avoid running the console.logs back to back — it will execute too quickly and you'll end up seeing the objects sorted by age back to back, instead of the objects sorted by name then sorted by age. Basically run the first console.log to confirm the output of objects sorted by name, then run the second console.log to confirm the objects sorted by age.

https://media.giphy.com/media/NEvPzZ8bd1V4Y/giphy.gif

And with that, you should have a basic understanding of how the sort method works and how to avoid some of the gotchas.

If you've enjoyed this article, feel free to check out my other JS array method articles:

JS Array Methods You Should Know: .map, .reduce, and .filter (ft. Chaining)

Javascript Basics: Use .push, .pop, .shift, and .unshift to Manipulate Arrays

Javascript: The Difference Between .slice and .splice

10 Javascript Array Methods You Should Know

As always, refer to MDN for more info:

.sort()

Feel free to reach out on any of my socials for questions, feedback, or just to connect / say hello 👋.

Top comments (0)