Categories
JavaScript Answers

How to Sort Arrays in JavaScript by Object Key Value?

Spread the love

To sort arrays in JavaScript by object key value, we can use the JavaScript array’s sort method.

For instance, we can write:

const arr = [{
  name: "alex"
}, {
  name: "clex"
}, {
  name: "blex"
}];
const sorted = arr.sort((a, b) => (a.name > b.name ? 1 : -1))
console.log(sorted)

to sort the arr array by the value of the name properties.

We call arr.sort with a callback that compare the name properties of entries a and b in the arr object.

If a.name is bigger than b.name , we return 1.

Otherwise, we return -1.

The comparison operator will compare 2 string’s by their lexical order.

Therefore, sorted is:

[
  {
    "name": "alex"
  },
  {
    "name": "blex"
  },
  {
    "name": "clex"
  }
]

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.