DEV Community

anjan-dutta
anjan-dutta

Posted on

Javascript sort array of objects

Before trying to sort array of objects in javascript, we must check if all objects in that array has a common property name.

For example, below is our sample object:

let obj = [
{a: 2, b: 1, c: 3},
{a: 7, c: 8},
{b: 0, c: 5}
];
Enter fullscreen mode Exit fullscreen mode

Can you identify the common property name among all the array objects? Yes, ‘c’ is the common property among all the objects. So, we can sort these objects by the property ‘c’.

Next, we have to check what is the data type of the common object property. An object can have multiple types of properties. Type means data type of any property. In this article, I have explained the three most commonly used type based sorting.

Three most commonly used object property based sorting in javascript.

  • Sort array of objects in javascript by a string property
  • Sort array of objects in javascript by number property
  • Sort array of objects in javascript by date property

There are many approaches that we can use to code all three of these solutions. Manually we can compare object to object by property values and sort objects. Go for it and give it a try if you love solving algorithms problems.

Or, we can use inbuilt javascript functions to quickly code these solutions. For this article we are going to use the sort() function.

If you do not know what is a sort() function then do not worry. I am going to explain it next.

The sort function is powerful. It is easy to use and reduces the requirement of any external library for sorting.

The sort() function takes only one parameter, a compare function. Compare function contains the logic that performs an in-place comparison between two values and applies sort logically.

Below is an example, to sort an integer array in ascending order.

var numbers = [40, 100, 1, 5, 25, 10];

numbers.sort(function(a, b){return b-a});

console.log(numbers);  // [1, 2, 5, 10, 25, 40, 100]
Enter fullscreen mode Exit fullscreen mode

Read more...

Top comments (2)

Collapse
 
ahmedmansoor012 profile image
Mansoor Ahmed

Nice post. Thanks for sharing.

Collapse
 
anjandutta profile image
anjan-dutta

glad that you liked it.