This page looks best with JavaScript enabled

Sort Arrays on Multiple Attributes

 ·   ·  ☕ 2 min read

You can quite easily sort arrays on multiple attributes using a simple Array.sort().

Consider this array -

1
2
3
4
5
6
const students = [
  { name: "Rama", grade: 10, class: 5 },
  { name: "Kris", grade: 7, class: 1 },
  { name: "Jan", grade: 8, class: 5 },
  { name: "Kris", grade: 5, class: 7 }
];

Sorting based on grade is easy.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const sorted = students.sort((a, b) => a.class - b.class);
console.log("sorted: ", sorted);

/* output
[
  { name: 'Kris', grade: 7, class: 1 },
  { name: 'Rama', grade: 10, class: 5 },
  { name: 'Jan', grade: 8, class: 5 },
  { name: 'Kris', grade: 5, class: 7 }
]
*/

If we add a further or condition in the sort criteria, Javascript can sort on both attributes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const sorted = students.sort((a, b) => a.class - b.class || a.grade - b.grade);
console.log("sorted: ", sorted);

/* output
[
  { name: 'Kris', grade: 7, class: 1 },
  { name: 'Jan', grade: 8, class: 5 },
  { name: 'Rama', grade: 10, class: 5 },
  { name: 'Kris', grade: 5, class: 7 }
]
*/

The Array.sort() eliminates complex loops, is readable, and gets the work done.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things