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>
<html>
<body>
  <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) => a.name.localeCompare(b.name))
    console.log(sorted)
  </script>
</body>
</html>

Output:

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) => (a.name > b.name ? 1 : 1))
// Name Z to A
array?.sort((a, b) => (a.name > b.name ? -1 : 1))
// Sort by date
array.sort((a,b) =>  new Date(b.date) - new Date(a.date));
//For Ascending
a.sort((a,b)=> (a.name > b.name ? 1 : -1))

//For Descending
a.sort((a,b)=> (a.name < b.name ? 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;
}

<Array>.sort(sortAsc);
<Array>.sort(sortDesc);

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading