Languages
[Edit]
EN

JavaScript - sort array of strings

3 points
Created by:
p_agon
589

In this article, we would like to show you how to sort array of strings using JavaScript​​​​​​.

Quick solution:

// ONLINE-RUNNER:browser;

const array = ['C', 'A', 'B'];
array.sort();

console.log(array);  // ['A', 'B', 'C']

 

Sort in reverse order

To sort the array in reverse order, we need to change comparer.

// ONLINE-RUNNER:browser;

const array = ['C', 'A', 'B'];
array.sort((a, b) => -a.localeCompare(b));

console.log(array);  // ['C', 'B', 'A']

 

See also

  1. JavaScript - sort array

  2. JavaScript - sort array of integers

  3. JavaScript - sort array of objects

References

  1. Array.prototype.sort() - JavaScript | MDN
  2. Array.prototype.reverse() - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join