Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting strings in descending order in Javascript (Most efficiently)?

W3CSchools has this example:

var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); fruits.reverse(); 

Is this the most efficient way to sort strings in descending order in Javascript?

Update

One of the answers is using localeCompare. Just curious whether if we do reverse(), will that work for all locales (Maybe this is a separate question - Just let me know in the comments)?

like image 984
Ole Avatar asked Aug 26 '18 20:08

Ole


People also ask

Which sort is best for descending order?

Among the classical sorting algorithms, heap sort will do well when the input turns out to be (almost) sorted in descending order, as then the max-heap construction phase will involve (almost) no swaps (while the most swaps would occur when the input was already sorted in ascending order).

How do you sort descending in JavaScript?

To sort an array of strings in descending order: Call the sort() method on the array. Call the reverse() method on the result. The returned array will have its elements sorted in descending order.

Which function is used to sort values in descending order in JavaScript?

The sort() method, by default, reorganizes a given array into one in which the elements are presented in ascending order according to the English alphabet. Note: the reverse() method reorganizes a given array into descending order.

How does JavaScript sort strings?

Sort String in JavaScript is used to sort the strings according to alphabetical order i.e it converts the given elements into strings by comparing the UTF-16 code sequences into unit values.


2 Answers

If you consider

obj.sort().reverse(); 

VS

obj.sort((a, b) => (a > b ? -1 : 1)) 

VS

obj.sort((a, b) => b.localeCompare(a) ) 

The performance winner is : obj.sort().reverse().

Testing with an array of 10.000 elements, obj.sort().reverse() is faster than obj.sort( function ) (except on chrome), and obj.sort( function ) (using localCompare).

Performance test here :

var results = [[],[],[]]    for(let i = 0; i < 100; i++){    const randomArrayGen = () => Array.from({length: 10000}, () => Math.random().toString(30));    const randomArray = randomArrayGen();    const copyArray = x => x.slice();      obj = copyArray(randomArray);    let t0 = performance.now();    obj.sort().reverse();    let t1 = performance.now();      obj = copyArray(randomArray);    let t2 = performance.now();    obj.sort((a, b) => (a > b ? -1 : 1))    let t3 = performance.now();      obj = copyArray(randomArray);    let t4 = performance.now();    obj.sort((a, b) => b.localeCompare(a))    let t5 = performance.now();        results[0].push(t1 - t0);    results[1].push(t3 - t2);    results[2].push(t5 - t4);    }    const calculateAverage = x => x.reduce((a,b) => a + b) / x.length ;    console.log("obj.sort().reverse():                   " + calculateAverage(results[0]));  console.log("obj.sort((a, b) => (a > b ? -1 : 1)):   " + calculateAverage(results[1]));  console.log("obj.sort((a, b) => b.localeCompare(a)): " + calculateAverage(results[2]));
like image 192
colxi Avatar answered Sep 26 '22 02:09

colxi


Using just sort and reverse a > Z , that is wrong if you want to order lower cases and upper cases strings:

var arr = ["a","b","c","A","B","Z"];    arr.sort().reverse();    console.log(arr)//<-- [ 'c', 'b', 'a', 'Z', 'B', 'A' ] wrong!!!

English characters

var arr = ["a","b","c","A","B","Z"];    arr.sort((a,b)=>b.localeCompare(a))    console.log(arr)

Special characters using locales, in this example es (spanish)

var arr = ["a", "á", "b","c","A","Á","B","Z"];    arr.sort((a, b) => b.localeCompare(a, 'es', {sensitivity: 'base'}))      console.log(arr)

sensitivity in this case is base:

Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A.

like image 32
Emeeus Avatar answered Sep 26 '22 02:09

Emeeus