How to sort an array using sort() method in JavaScript?

In this article, we will show you how to sort an array using the sort() method in JavaScript.

We often come across situations where we need to arrange data in a particular order.

It’s essential to ensure that the data is sorted accurately because even the slightest inaccuracies can lead to problems or errors in our code.

Don’t worry! We’ve got your back because we will explore the process of sorting an array in JavaScript.

We’ll discuss the sort() method and explore techniques to achieve more precise and dependable results.

What is sort() method in JavaScript?

The Array.prototype.sort() or the sort() method is a built-in method in JavaScript that is used to sort the elements of an array in place and returns the reference to the same array, now sorted.

The default sorting order is ascending and is based on converting the elements into strings. The comparison is done by evaluating their sequences of UTF-16 code unit values.

Syntax

array.sort([compareFunction])

Parameters

📌compareFunction (optional)

The function determines how the array is sorted. If you provide a custom compare function, all non-undefined elements in the array will be sorted based on the values returned by that function.

If there are any undefined elements, they will be sorted to the end of the array without using the compare function.

If you don’t provide a compare function, the elements in the array will be converted to strings and sorted based on the Unicode code point value of each character.

Return value

The sort() method returns the reference to the same array, now sorted. The original array is modified and sorted in place.

What is the compare function?

The compare function is an optional parameter that can be passed to the sort() method in JavaScript. It is used to define a custom sorting order for the elements of an array.

The compare function should take two arguments, often referred to as a and b, and return a value that determines the sort order of the elements.

If the function returns a value less than 0, a is sorted before b.

If the function returns a value greater than 0, b is sorted before a.

If the function returns 0, the order of a and b will remain unchanged.

Here is an example of using a compare function to sort an array of numbers in ascending order:

const points = [10, 2, 5, 15, 25, 20];
points.sort(function(a, b) {return a - b});
console.log(points)

In our example, you can see that the compare function takes two arguments a and b, and returns the result of subtracting b from a.

This causes the sort() method to sort the elements of the array in ascending order.

Output:

[ 2, 5, 10, 15, 20, 25 ]

Different ways on how to sort an array using sort() method in JavaScript?

There are several ways to sort an array using the sort() method in JavaScript.

Alphabetical order

By default, the sort() method sorts strings alphabetically and numbers in ascending order.

Here’s the examples of sorting an array alphabetically in JavaScript using the sort() method:

const subjects = ["Math", "English", "Science", "Programming"];
subjects.sort();
console.log(subjects);

Output:

[ 'English', 'Math', 'Programming', 'Science' ]

Reverse order

To reverse the order of an array, you can first sort the elements of the array with the sort() command and then reverse the order with the reverse() command.

Here’s an example:

const subjects = ["Math", "English", "Science", "Programming"];
subjects.sort();
subjects.reverse();
console.log(subjects); 

Output:

[ 'Science', 'Programming', 'Math', 'English' ]

Ascending order

To sort an array of numbers in ascending order, you can use a compare function with the sort() method. The compare function compares two values and then sorts them according to the generated value.

Here’s an example:

const scores = [50, 20, 15, 35, 10];
scores.sort(function(a, b) {return a - b});
console.log(scores); 

Output:

[ 10, 15, 20, 35, 50 ]

Descending order

To sort an array of numbers in descending order, you can use a compare function with the sort() method.

The compare function compares two values and then sorts them according to the generated value.

Here’s an example:

const scores = [50, 20, 15, 35, 10];
scores.sort(function(a, b) {return b - a});
console.log(scores); 

Examples of JavaScript sorting array of numbers 

Sorting an array of numbers in ascending order:

const grades = [75, 95, 85, 90, 98, 80];
grades.sort(function(a, b) {return a - b});
console.log(grades);

Output:

[ 75, 80, 85, 90, 95, 98 ]

Sorting an array of numbers in descending order:

const grades2 = [75, 95, 85, 90, 98, 80];
grades2.sort(function(a, b) {return b - a});
console.log(grades2);

Output:

[ 98, 95, 90, 85, 80, 75 ]

Define the comparison function using the arrow function:

const grades3 = [75, 95, 85, 90, 98, 80];
grades3.sort((a,b) => {
    if(a > b) return 1;
    if(a < b) return -1;
    return 0;
});

console.log(grades3);

Output:

[ 75, 80, 85, 90, 95, 98 ]

Sorting JavaScript array of objects

To sort an array of objects in JavaScript, you can use the sort() method with a compare function.

The compare function helps you to write your own logic for sorting the array of objects.

It allows you to sort arrays of objects by strings, integers, dates, or any other custom property.

Here is an example of sorting an array of objects by a string property:

const students = [
  { firstName: "Xharlz", lastName: "Darwin", age: 20 },
  { firstName: "Eunice", lastName: "Smith", age: 18  },
  { firstName: "Beatrice", lastName: "Gomez", age: 19  }
  ];

students.sort((a, b) => {
let fa = a.firstName.toLowerCase(),
fb = b.firstName.toLowerCase();

if (fa < fb) { return -1; } if (fa > fb) {
return 1;
}
return 0;
});

console.log(students);

Output:

[
  { firstName: 'Beatrice', lastName: 'Gomez', age: 19 },
  { firstName: 'Eunice', lastName: 'Smith', age: 18 },
  { firstName: 'Xharlz', lastName: 'Darwin', age: 20 }
]

This code creates an array of students objects and sorts them by the firstName property in ascending order.

The sort() method takes a compare function as a parameter, which defines the sort order.

In this example, the compare function converts the firstName property of each students object to lowercase and compares them to determine their order.

How to sort array of strings with non-ASCII characters?

To sort an array of strings with non-ASCII characters, you can use the localeCompare() method.

This method returns a numeric value indicating whether a reference string comes before or after or is the same as the given string in sort order.

Here is an example of sorting an array of strings with non-ASCII characters using the localeCompare() method:

const words = ['éclair', 'château', 'café', 'croissant'];
words.sort((a, b) => a.localeCompare(b));
console.log(words);

[ 'café', 'château', 'croissant', 'éclair' ]

In this example, the sort() method takes a compare function as a parameter, which defines the sort order.

The compare function uses the localeCompare() method to compare the elements of the array and sort them in ascending order.

Output:

[ 'café', 'château', 'croissant', 'éclair' ]

Conclusion

In this article, this article explore the process on how to sort an array in JavaScript using the sort() method.

Sorting an array means arranging its elements in a specific order. The sort() method is built into JavaScript and can sort the elements of an array in ascending order by default.

You can also use a custom compare function with the sort() method to sort the array in a specific way. The compare function allows us to define our own rules for sorting.

For instance, we can sort an array of numbers in ascending or descending order, and we can sort an array of objects based on specific properties.

We are hoping that this article provides you with enough information that helps you understand the JavaScript sort array.

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Leave a Comment