Skip to content

Sort array of objects JavaScript by key value | Example code

  • by

Use the array sort method to Sort an array of objects JavaScript by key value. The sort() method accepts a comparator function.

myArray.sort((a, b) => a.distance - b.distance)

This function accepts two arguments (both presumably of the same type) and its job is to determine which of the two comes first.

It does this by returning an integer

  • Negative (less-than zero): The first argument comes first
  • Positive (greater-than zero): The second argument comes first
  • Zero: The arguments are considered equal for sorting

When you’re dealing with numeric values, the simplest solution is to subtract the second value from the first which will produce an ascending order result.

Sort array of objects JavaScript by key value

Simple example code call arr.sort with a callback that sorts the entries by the name property lexically with localeCompare.

<!DOCTYPE html>
  <script >
    const arr = [{
      name: 'Bob',
      artist: 'rudy'
      name: 'Any',
      artist: 'drusko'
      name: 'Tiff',
      artist: 'needell'
      name: 'Rokcy',
      artist: 'gear'

    const sorted = arr.sort((a, b) =>


Sort array of objects JavaScript by key value

More examples

// Price Low To High
array?.sort((a, b) => (a.price > b.price ? 1 : -1))
// Price High To Low
array?.sort((a, b) => (a.price > b.price ? -1 : 1))
// Name A to Z
array?.sort((a, b) => ( > ? 1 : 1))
// Name Z to A
array?.sort((a, b) => ( > ? -1 : 1))
// Sort by date
array.sort((a,b) =>  new Date( - new Date(;
//For Ascending
a.sort((a,b)=> ( > ? 1 : -1))

//For Descending
a.sort((a,b)=> ( < ? 1 : -1))
//Sort Objects in array Descending order
const sortDesc(a,b) => {
  return b.timestamp - a.timestamp;

//Sort Objects in array Ascending order
const sortAsc(a,b) => {
  return a.timestamp - b.timestamp;


Do comment if you have any doubts or suggestions on this Js Array object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *