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.
constfruits=["Apple","Orange","Banana","Papaya","Guava"]fruits.sort();console.log(fruits);constnumberz=[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.constnumberz2=[10,9,2,1,100]numberz2.sort((a,b)=>a-b);console.log(numberz2);constnumberz3=[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.