Sort JavaScript Array by Key in Ascending & Descending Order
In this article, we are going to learn how to sort JavaScript array by key. Let’s take an array:
let products = [
{name: "Product 1", price: 32.34},
{name: "Product 2", price: 10.23},
{name: "Product 3", price: 22.75},
{name: "Product 4", price: 16.95},
]
We’ll sort the array by price in ascending & descending order. We will use array.sort()
method. Let’s see the syntax:
// ascending order
array.sort((a, b) => a.key - b.key)
// descending order
array.sort((a, b) => b.key - a.key)
Ascending Order
We’ve seen the syntax. Now let’s apply the ascending formula on our products array.
products.sort((a, b) => a.price - b.price)
If you print the result in the console, the result will look like:

Descending Order
Like ascending, let’s apply descending order:
products.sort((a, b) => b.price- a.price)
and the result will look like:

Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)