From the course: JavaScript: Arrays

Unlock the full course today

Join today to access over 24,800 courses taught by industry experts.

Order arrays with sort

Order arrays with sort - JavaScript Tutorial

From the course: JavaScript: Arrays

Order arrays with sort

- [Teacher] As the name of the array method implies, sort we'll sort an array. By default, the contents of the array will be sorted as strings in ascending order, which is smallest to largest. If we haven't yet have strings that we need to sort alphabetically, we can simply apply sort. The compare function can be written in one of two ways. The first is as a function expression that explicitly returns a value. The second example uses ES6 syntax to implicitly return the function. The compare function can be used to alter the default sort order. The function should return a value that is either positive, negative, or zero. The values are then sorted based on the return value. The compare function will compare all of the values in an array. Two at a time, altering the order accordingly. Let's use this as an example. We have values a and b, and we are comparing a minus b in order to sort from lowest to highest.…

Contents