Categories
JavaScript Answers

How to sort array on key value with JavaScript?

Spread the love

Sometimes, we want to sort array on key value with JavaScript.

In this article, we’ll look at how to sort array on key value with JavaScript.

How to sort array on key value with JavaScript?

To sort array on key value with JavaScript, we can use the array sort method.

For instance, we write:

const arr = [{
    name: 'bob',
    artist: 'rudy'
  },
  {
    name: 'johhny',
    artist: 'drusko'
  },
  {
    name: 'tiff',
    artist: 'needell'
  },
  {
    name: 'top',
    artist: 'gear'
  }
];

const sorted = arr.sort((a, b) => a.name.localeCompare(b.name))
console.log(sorted)

to call arr.sort with a callback that sort the entries by the name property lexically with localeCompare.

Therefore, sorted is:

[{
  artist: "rudy",
  name: "bob"
}, {
  artist: "drusko",
  name: "johhny"
}, {
  artist: "needell",
  name: "tiff"
}, {
  artist: "gear",
  name: "top"
}]

Conclusion

To sort array on key value with JavaScript, we can use the array sort method.

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 *