Understanding Javascript's Array Sort
Tags: javascript, arrays, codenewbie, tips
Published: 2021-01-07 10:45:42

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](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

```jsx
let colors = ["orange","green","blue","red"]
console.log(colors.sort()) // ["blue", "green", "orange", "red"]
```

![https://media.giphy.com/media/l1KVaJ2P5v9YrhrOg/giphy.gif](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.

```jsx
// 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 }]
```

![https://media.giphy.com/media/FbhvYtCgfa170yRpV9/giphy.gif](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:

```jsx

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;
}
```

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 :

```jsx
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]

```

Example with objects:

```jsx
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}]
```

**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](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)](https://dev.to/antdp425/js-array-methods-you-should-know-map-reduce-and-filter-ft-chaining-e2i)

[Javascript Basics: Use .push, .pop, .shift, and .unshift to Manipulate Arrays](https://dev.to/antdp425/javascript-basics-use-push-pop-shift-and-unshift-to-manipulate-arrays-48ab)

[Javascript: The Difference Between .slice and .splice](https://dev.to/antdp425/javascript-the-difference-between-slice-and-splice-mh0)

[10 Javascript Array Methods You Should Know](https://dev.to/antdp425/10-javascript-array-methods-you-should-know-1de8)

As always, refer to MDN for more info:

.[sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)

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