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) => ( > ? 1 : -1))

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 is bigger than , 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. Required fields are marked *