Introduction
Sorting arrays is a fundamental operation in programming. In JavaScript, the sort()
method allows you to easily sort arrays either in ascending or descending order by using custom comparison functions. This guide will walk you through writing a JavaScript program to sort an array in both ascending and descending order.
Problem Statement
Create a JavaScript program that:
- Accepts an array of integers.
- Sorts the array in ascending order.
- Sorts the array in descending order.
- Displays the sorted arrays.
Example:
- Input:
[5, 2, 9, 1, 5, 6]
- Output:
- Ascending:
[1, 2, 5, 5, 6, 9]
- Descending:
[9, 6, 5, 5, 2, 1]
- Ascending:
Solution Steps
- Initialize the Array: Provide an array of integers to be sorted.
- Sort in Ascending Order: Use the
sort()
method with a custom comparator function to sort the array in ascending order. - Sort in Descending Order: Use the
sort()
method with a custom comparator function to sort the array in descending order. - Display the Result: Output the sorted arrays.
JavaScript Program
// JavaScript Program to Sort an Array in Ascending and Descending Order
// Author: https://www.rameshfadatare.com/
function sortArray(arr) {
// Step 1: Sort the array in ascending order
const ascending = arr.slice().sort((a, b) => a - b);
// Step 2: Sort the array in descending order
const descending = arr.slice().sort((a, b) => b - a);
// Step 3: Display the sorted arrays
console.log("Original Array:", arr);
console.log("Sorted in Ascending Order:", ascending);
console.log("Sorted in Descending Order:", descending);
}
// Example usage
const numbers = [5, 2, 9, 1, 5, 6];
sortArray(numbers);
Explanation
Step 1: Sort in Ascending Order
- The
sort()
method is used with a comparator function(a, b) => a - b
, which ensures that the array is sorted in ascending order. Theslice()
method creates a shallow copy of the original array to avoid modifying it.
Step 2: Sort in Descending Order
- Similarly, to sort in descending order, the comparator function
(a, b) => b - a
is used, which sorts the array from largest to smallest.
Step 3: Display the Sorted Arrays
- Both the original and sorted arrays are displayed using
console.log()
.
Output Example
Original Array: [ 5, 2, 9, 1, 5, 6 ]
Sorted in Ascending Order: [ 1, 2, 5, 5, 6, 9 ]
Sorted in Descending Order: [ 9, 6, 5, 5, 2, 1 ]
Example with Different Input
const numbers = [10, 20, 5, 8, 12];
sortArray(numbers);
Output:
Original Array: [ 10, 20, 5, 8, 12 ]
Sorted in Ascending Order: [ 5, 8, 10, 12, 20 ]
Sorted in Descending Order: [ 20, 12, 10, 8, 5 ]
Conclusion
This JavaScript program demonstrates how to sort an array in both ascending and descending order using the sort()
method with custom comparator functions. The program efficiently handles sorting and preserves the original array, making it a flexible solution for array sorting operations in JavaScript.
Comments
Post a Comment
Leave Comment