sort() :
- It is used to arrange elements of an array.
- It modifies the original array.
- By default, the sort() method converts all elements into strings and sorts them in ascending order based on their Unicode values.
- Works perfectly for strings.
-
For numbers, the default comparator converts elements to strings, which causes unexpected results with numbers. So we must provide a compare function as an argument. The function compares two elements (a and b) and returns a value.
- Negative value: a is placed before b.
- Positive value: b is placed before a.
- Zero: The relative order remains unchanged.
const fruits = ["Apple","Orange","Banana","Papaya","Guava"]
fruits.sort();
console.log(fruits);
const numberz = [10, 9, 2, 1, 100]
numberz.sort();
console.log(numberz); // without compare function Β [1, 10, 100, 2, 9]. Because elements are converted into string first.
const numberz2 = [10, 9, 2, 1, 100]
numberz2.sort((a,b)=>a-b);
console.log(numberz2);
const numberz3 = [10, 9, 2, 1, 100]
numberz2.sort((a,b)=>b-a);
console.log(numberz3);
Output :
['Apple', 'Banana', 'Guava', 'Orange', 'Papaya']
[1, 10, 100, 2, 9]
[1, 2, 9, 10, 100]
[100, 10, 9, 2, 1]
Top comments (1)
Also
Array.toSortedif you don't want to modify the original.