---
description: Sort method of array helpers
---

# $.array.sort

You may want to create ordering or to sort array of items in ascending or descending, you need to use this `sort` helper, here we provide sorting in numbers, strings, array of objects and callback or compare function.

```
$.array.sort(arrayofItems, sortBy)

// Example:
const fromNumbers = [5, 3, 6, 4, 2, 1, 7]
$.array.sort(fromNumbers, 'asc')
//=> [1, 2, 3, 4, 5, 6, 7]

const fromStrings = ['Aba', 'Cara', 'Data', 'Baca', 'Eja', 'Fasih', 'Gara']
$.array.sort(fromStrings, 'desc')
//=> ['Gara', 'Fasih', 'Eja',  'Data', 'Cara', 'Baca', 'Aba']
```

If you guys want to order or sort the array of objects, you can use `sortBy` helper for this.

```
$.array.sortBy(fromArray, objectPropKey, sortBy)

// Example:
const fromArray = [
  { id: 1, name: 'Hanbal Tedir', office: 'Jakarta', age: 30 },
  { id: 2, name: 'Dawoud Tedir', office: 'Medan', age: 27 },
  { id: 3, name: 'Harist Tedir', office: 'Sigli', age: 15 },
  { id: 4, name: 'Tedir Ghazali', office: 'Banda Aceh', age: 29 },
  { id: 5, name: 'Hanbal Usman', office: 'Langsa', age: 27 },
  { id: 6, name: 'Dawoud Usman', office: 'Pidie', age: 25 },
  { id: 7, name: 'Harist Usman', office: 'Samarinda', age: 18 },
  { id: 8, name: 'Ghazali Usman', office: 'Balikpapan', age: 45 },
  { id: 9, name: 'Bukhari Usman', office: 'Makassar', age: 44 },
  { id: 10, name: 'Boyhaki Usman', office: 'Jaya Pura', age: 35 },
  { id: 11, name: 'Zulkifli Usman', office: 'Manado', age: 56 },
  { id: 12, name: 'Teuku Usman', office: 'Ternate', age: 58 }
]
$.array.sortBy(fromArray, 'name', 'desc')
//=> [
//  { id: 11, name: 'Zulkifli Usman', office: 'Manado', age: 56 },
//  { id: 12, name: 'Teuku Usman', office: 'Ternate', age: 58 },
//  { id: 4, name: 'Tedir Ghazali', office: 'Banda Aceh', age: 29 },
//  { id: 7, name: 'Harist Usman', office: 'Samarinda', age: 18 },
//  { id: 3, name: 'Harist Tedir', office: 'Sigli', age: 15 },
//  { id: 5, name: 'Hanbal Usman', office: 'Langsa', age: 27 },
//  { id: 1, name: 'Hanbal Tedir', office: 'Jakarta', age: 30 },
//  { id: 8, name: 'Ghazali Usman', office: 'Balikpapan', age: 45 },
//  { id: 6, name: 'Dawoud Usman', office: 'Pidie', age: 25 },
//  { id: 2, name: 'Dawoud Tedir', office: 'Medan', age: 27 },
//  { id: 9, name: 'Bukhari Usman', office: 'Makassar', age: 44 },
//  { id: 10, name: 'Boyhaki Usman', office: 'Jaya Pura', age: 35 }
//]
```

Or if you guys want to compare manually by yourself, you can use callback or compare function that we provide in `sortWith` helper.

```
$.array.sortWith(fromArray, callbackOrCompareFunction)

// Example:
const fromArray = ['premier', 'réservé', 'communiqué', 'café', 'adieu', 'éclair']

$.array.sortWith(fromArray, (a, b) => a.localeCompare(b))
//=> ['adieu', 'café', 'communiqué', 'éclair', 'premier', 'réservé']

$.array.sortWith(fromArray, (a, b) => b.localeCompare(a))
//=> ["réservé", "premier", "éclair", "communiqué", "café", "adieu"]
```
