In JavaScript, you can use the sort() method to sort an array of strings. By default, the sort() method sorts the elements of an array in alphabetical order. Here is an example:
let fruits = ["apple", "banana", "cherry"];
fruits.sort();
console.log(fruits); // ["apple", "banana", "cherry"]
In this example, the sort() method sorts the elements of the fruits array in alphabetical order, and the result is [“apple”, “banana”, “cherry”].
You can also pass a comparison function as an argument to the sort() method, to define a custom sort order. The comparison function should take two arguments, and should return a negative, zero, or positive value, depending on the order of the elements.
let numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers); // [1,2,3,4,5]
In this example, the sort() method uses the comparison function to sort the elements of the numbers array in ascending numerical order. The function (a, b) => a – b compares two numbers and returns the difference.
You can also use sort() with the arrow function
let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1,2,3,4,5]
In this way, you can sort an array of strings or numbers in JavaScript using the sort() method.
Also Read:
- What Is a Web Worker In JavaScript?
- ECMAScript vs JavaScript
- What Is Strict Mode In JavaScript?
- Arrow Functions In JavaScript
- Difference Between Node.js and AngularJS With Example
- Difference Between == And === In JavaScript
- What Is JSON In JavaScript
- How To Go Back To Previous Page In JavaScript?
- How To Detect A Mobile Device With JavaScript?
- How To Close The Current Tab In A Browser Window Using JavaScript?
- How To Convert Input Text To Uppercase While Typing Using JavaScript?
- How To Show A Confirmation Message Before Delete In JavaScript?
- How To Detect Browser or Tab Closing In JavaScript?
- How To Get Hash Value From URL Using JavaScript?
- How To Get The Name, Size, And Type Of A File In JavaScript?
- Run JavaScript From The Command Line