Sorting Array of Objects using sort() 📊
If you've ever needed to sort an Array of Objects, you've probably heard of the sort()
method. But did you know that you can customize the sorting according to your needs?
The sort()
method accepts an optional comparison function as a parameter, which defines the sorting criteria for the elements of the Array. This function takes two parameters, which represent two elements of the Array to be compared, and should return a negative number if the first element is less than the second, a positive number if the second is less than the first, and zero if they are equal.
For example, imagine you have an Array of Objects representing a list of students, and each Object has two properties: "name" and "grade". To sort this list in alphabetical order by name, you can use the sort()
method with the following comparison function:
studentList.sort((studentA, studentB) => { if (studentA.name < studentB.name) { return -1; } else if (studentA.name > studentB.name) { return 1; } else { return 0; }});
In this example, the comparison function checks if the name of studentA
is less than the name of studentB
. If so, it returns -1
. If it is greater, it returns 1
. If they are equal, it returns 0
. With this function, the sort()
method sorts the student list in alphabetical order by name.
But what if you wanted to sort the list in descending order by grade? Just change the comparison function:
studentList.sort((studentA, studentB) => studentB.grade - studentA.grade);
In this case, the comparison function subtracts the grade of studentA
from the grade of studentB
, which results in a positive number if the grade of studentB
is higher than that of studentA
, and a negative number if it is lower. With this function, the sort()
method sorts the student list in descending order by grade.
It's worth noting that the sort()
method modifies the original Array and does not create an ordered copy. If you want to keep the original Array intact, you need to create a copy before sorting it.
So, did you like learning more about the sort()
method? Have you used it to sort Arrays of Objects before? If you have any questions, feel free to ask in my Instagram question box, where I'm here to help.
Let's go! 🦅