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:
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.