Javascript Array Sort
Array sorting allows us to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array.
Sorting an array
This method sorts an array alphabetically.
Input:-
Output:-
Reversing an array
This reverse() method reverses the elements in an array. We can use it to sort an array in descending order.
Input:-
Output:-
Sorting an array of objects by a numeric property
To sort an array of objects by a numeric property, you can use the sort()
method in JavaScript along with a comparison function. Here's an example using an array called employees
with objects containing properties like name
, age
, and designation
:
Input:-
Output:-
In this example, the sort()
method is called on the employees
array, and a comparison function is provided as an argument. The comparison function takes two objects from the array (a
and b
) and compares their age
properties.
Inside the comparison function, the difference between a.age
and b.age
is returned. This subtraction will result in a negative value if a.age
is less than b.age
, a positive value if a.age
is greater than b.age
, and 0 if they are equal.
After sorting, the employees
array will be sorted in ascending order based on the age
property.
You can modify the comparison function to compare and sort by other numeric properties like designation
or any other numeric property in a similar manner.
Sorting an array of objects by a string property
To sort an array of objects by a string property, you can use the sort()
method in JavaScript along with a comparison function. Here's an example using an array called employees
with objects containing properties like name
, age
, and designation
:
Input:-
Output:-