How to usethe sort method in Javascript
In this approach, A function sortAsc to sort an array in ascending order. The arr parameter represents the input array. It creates a copy of the array using slice() to avoid modifying the original array. The sort() method arranges elements in ascending order based on the return value of the comparison function (a, b) => a – b, subtracting b from a. Finally, it returns the sorted array.
Example: This example shows the implementation of the above-explained approach.
function sortAsc(arr) {
return arr.slice().sort((a, b) => a - b);
}
const array = [5, 3, 9, 1, 7];
const sortedArray = sortAsc(array);
console.log("Sorted Array (Ascending):", sortedArray);
Output
Sorted Array (Ascending): [ 1, 3, 5, 7, 9 ]
JavaScript Program to Sort the Elements of an Array in Ascending Order
Sorting an array in ascending order means arranging the elements from smallest element to largest element. we will learn to sort an array in ascending order in JavaScript.
These are the following methods:
Table of Content
- Using the sort method
- Using a for loop
- Using Insertion Sort
Contact Us