DEV Community

Bogdan Varlamov
Bogdan Varlamov

Posted on

JavaScript Array Methods: Understanding `sort`

Image description

After exploring the filter method, let's take a quick look at another array method: sort. The function of this method is apparent from its nameโ€”it sorts the items in an array.

A Simple Example

const numbers = [10, 1, 20, 2]
numbers.sort() // [1, 10, 2, 20]
Enter fullscreen mode Exit fullscreen mode

At first glance, the sorting doesn't seem to work as expected. Instead of the anticipated [1, 2, 10, 20], we get [1, 10, 2, 20].

Why does this happen? By default, sort (when used without parameters) converts the elements into strings and compares them based on their sequences of UTF-16 code units values. This default behavior works well for strings, such as sorting words alphabetically, but can yield unexpected results with numbers.

To correct this behavior, we can provide a callback function to the sort method:

const numbers = [10, 1, 20, 2]
numbers.sort((a, b) => a - b) // [1, 2, 10, 20]
Enter fullscreen mode Exit fullscreen mode

The callback function takes two arguments, a and b. The function's body compares these values, sorting the items from smallest to largest. If we reverse the comparison to b - a, we'd sort from largest to smallest.

Practical Application

Let's apply this method in a practical scenario. Continuing from our previous post on the filter method, we have the productsWithDiscount array. Now, we want to sort this array by price, from the lowest to the highest:

console.log(productsWithDiscount)
// [
//   {name: 'chicken fille', price: 16, isOnSale: true},
//   {name: 'Almond milk', price: 11, isOnSale: true},
//   {name: 'Mango', price: 7, isOnSale: true}
// ]

productsWithDiscount.sort((a, b) => {
  return a.price - b.price
})

console.log(productsWithDiscount)
// [
//   {name: 'Mango', price: 7, isOnSale: true}
//   {name: 'Almond milk', price: 11, isOnSale: true},
//   {name: 'chicken fille', price: 16, isOnSale: true},
// ]
Enter fullscreen mode Exit fullscreen mode

Now, we're able to display products on the discount page starting with the items that have the lowest price, enhancing the shopping experience for our users.

Thanks for hanging out! Hit subscribe for more! ๐Ÿ‘‹

Top comments (0)