You are on page 1of 2

Sorting in js

Sorting in JavaScript
Sorting is the process of arranging the elements of an array in a specific order. In
JavaScript, the sort() method is used to sort arrays. The sort() method takes an
optional argument, which is a function that compares two elements of the array. If the
optional argument is not provided, the sort() method will sort the elements in
ascending order.
Sorting Arrays of Strings
To sort an array of strings, you can use the following code:

const strings = ["Apple", "Banana", "Orange"];

strings.sort();

console.log(strings); // ["Apple", "Banana", "Orange"]

In this example, the sort() method will sort the elements of the strings array in
ascending order. The elements will be sorted by their ASCII values.
Sorting Arrays of Numbers
To sort an array of numbers, you can use the following code:

const numbers = [10, 5, 2];

numbers.sort();

console.log(numbers); // [2, 5, 10]

In this example, the sort() method will sort the elements of the numbers array in
ascending order. The elements will be sorted by their numerical values.
Using a Function Argument with sort()

You can also use the sort() method to sort arrays of objects. To do this, you need to
provide a compare function as the optional argument to the sort() method. The
compare function should take two objects as arguments and return a negative value if

Sorting in js 1
the first object is less than the second object, a positive value if the first object is greater
than the second object, and 0 if the two objects are equal.
The following code shows how to sort an array of objects by the name property:

const objects = [{ name: "John Doe", age: 30 }, { name: "Jane Doe", age: 25 }];

objects.sort((a, b) => a.name.localeCompare(b.name));

console.log(objects); // [{ name: "Jane Doe", age: 25 }, { name: "John Doe", age: 30 }]

In this example, the sort() method will sort the elements of the objects array by the
name property. The elements will be sorted in ascending order, according to the locale-

aware comparison of the name properties.

Sorting in js 2

You might also like