Sorting Array of Objects

Modified on Thu, 4 Jul at 12:12 AM

An array of objects is a collection of objects. Consider the following array of objects:

const items = [

  { name: "Alpha", value: 23 },
  { name: "Bravo", value: 42 },
  { name: "Echo", value: 31 },
  { name: "Foxtrot", value: 56 },
  { name: "Charlie", value: 17 },
  { name: "Delta", value: -9 },

];

To sort the array based on the `value` property, use the `.sort()` method with a comparator function:

items.sort((a, b) => a.value - b.value);

After running the above snippet the items array will be sorted as:

const items = [

  { name: "Delta", value: -9 },
  { name: "Charlie", value: 17 },
  { name: "Alpha", value: 23 },
  { name: "Echo", value: 31 },
  { name: "Bravo", value: 42 },
  { name: "Foxtrot", value: 56 },

];


In this example, the comparator function `(a, b) => a.value - b.value` compares the `value` properties of two objects in the `items` array:

  • If `a.value` is more than `b.value`, the function returns a positive value meaning `a` should come after `b`.
  • If `a.value` is less than `b.value`, the function returns a negative value meaning `a` should come before `b`.
  •  If `a.value` is equal to `b.value`, the function returns zero meaning `a` and `b` are equal in order.

If we wanted to sort the array in descending order based on the `value` property, then we would use the `.sort()` as

items.sort((a, b) => b.value - a.value);

After running the above snippet the items array will be sorted as:

const items = [

  { name: "Foxtrot", value: 56 },
  { name: "Bravo", value: 42 },
  { name: "Echo", value: 31 },
  { name: "Alpha", value: 23 },
  { name: "Charlie", value: 17 },
  { name: "Delta", value: -9 },

];


Takeaways / Best Practices:

  • Be mindful of potential edge cases, such as handling `NaN` or `Infinity` values, if they exist in the array.
  • Always consider the specific sorting requirements and adjust the compare function accordingly.


Here are a few problems where these concepts are used:



Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article