Before we start, let’s take a look at array.prototype.sort ().

Array.prototype.sort()

The array.prototype.sort () method sorts the elements of an Array using an in-place algorithm and returns the Array.

There are two things to note when using the array.prototype.sort () method:

  • By default, this method converts all elements in the array to String before sorting.
  • Strings are sorted by ASCII code.
const months = ['March'.'Jan'.'Feb'.'Dec']
months.sort()
console.log(months) // ["Dec", "Feb", "Jan", "March"]

const arr = [1.30.4.21.100000]
array1.sort()
console.log(arr) // [1, 100000, 21, 30, 4]
Copy the code

As you can see, the original array of values is sorted according to the rules mentioned above. How do we solve this? To look down.

Array.prototype.sort() is a higher-order function that can pass in a function that specifies an order.

const arr = [8.2.1.4.5.0]

arr.sort((a, b) = > {
  if (a > b) return 1
  if (b > a) return -1
  return 0
}) // [0, 1, 2, 4, 8, 12]
Copy the code

More succinctly:

const arr = [1.8.12.4.2.0]
// Sort in ascending order
arr.sort((a, b) = > a - b) // [0, 1, 2, 4, 8, 12]
// Sort in descending order
arr.sort((a, b) = > b - a) // [12, 8, 4, 2, 1, 0]
Copy the code

The trick depends on array.prototype.sort () expecting a positive or negative value to perform an exchange between two elements.

If you are using an array of strings, you can use the String. The prototype. LocaleCompare (), because it provides greater flexibility, by considering the specific regional Settings and its unique requirements:

const arr = ['Hi'.'Hola'.'Hello']

// Sort in ascending order
arr.sort((a, b) = > a.localeCompare(b)) // ['Hello', 'Hi', 'Hola']
// Sort in descending order
arr.sort((a, b) = > b.localeCompare(a)) // ['Hola', 'Hi', 'Hello']
Copy the code

Objects can be sorted by a property

Depending on the scenario, you may need keys, values, or date fields to sort the JavaScript array objects.

Use Array. The prototype. The sort () and String. The prototype. LocaleCompare sort () to the String data.

let arr = [
  { name: 'HTML'.dataTime: '1999-01-20' },
  { name : 'JavaScript'.dataTime: '2000-07-22' },
  { name : 'CSS'.dataTime: '2020-08-20'}]const sortData = (data, order = 'asc') = > {
  if(order == 'asc') {return data.sort((a, b) = > a.dataTime.localeCompare(b.dataTime))
  } else {
    return data.sort((a, b) = > b.dataTime.localeCompare(a.dataTime))
  }
  return data
}

console.log(sortData(arr))
Copy the code