How to Sort an Array of Objects in Javascript

Monday, April 12, 2021 • 2 minutes to read

Javascriptto-the-point2021to-the-pointjavascript

Using the sort method, we can sort the array of objects by the property of the object.

The sort method will change the persons array instead of creating a copy of it. sort works by reference not by value.

1const persons = [
2    {name: "John", age: 35},
3    {name: "Steve", age: 24},
4    {name: "Ben", age: 49}
5]

Syntax

 1array.sort(function (arg1, arg2) {
 2	// arg1 is smaller than arg2 
 3	// example: (2-4) = negative (less than 0)
 4	if(arg1 < arg2) {
 5		return -1; // in ascending order
 6        // return 1; // in descening order
 7	} 
 8	// arg1 is larger than arg2
 9	// example: (6-2) = positive (greater than 0)
10	else if (arg1 > arg2) {
11		return 1; // in ascending order
12         // return -1; // in descening order
13	} 
14	// arg1 is equal to arg2
15	return 0;
16} )

Sort the object by name

 1persons.sort((p1, p2) => {
 2    // to ignore the case sensitivity
 3    const arg1 = p1.name.toLowerCase();
 4    const arg2 = p2.name.toLowerCase();
 5	if(arg1 < arg2) {
 6		return -1;
 7	} else if (arg1 > arg2) {
 8		return 1;
 9	}
10	return 0;
11});
12console.log(persons);

Output

1[
2    {"name":"Ben","age":49},
3    {"name":"John","age":35},
4    {"name":"Steve","age":24}
5]

We have used arrow => function expression include in ES2015 instead of function. Both are correct.

Sort the object by age

1persons.sort((arg1, arg2) => {
2	return arg1.age - arg2.age; // for ascending order
3	// return arg2.age - arg1.age; // for decending order
4})
5// Or use the short format
6persons.sort((arg1, arg2) => arg1.age - arg2.age;)
7
8console.log(persons);

Output

1[
2    {"name":"Steve","age":24},
3    {"name":"John","age":35},
4    {"name":"Ben","age":49}
5]

Javascriptto-the-point2021to-the-pointjavascript

PreviousHow to Convert an Array to a String in Javascript

NextHow to Remove Consecutive Characters From a String