Sort and reverse on arrays

PHOTO EMBED

Sun Nov 03 2024 15:08:03 GMT+0000 (Coordinated Universal Time)

Saved by @signup_returns #html

// sortAndReverse.js

// Example arrays for demonstration
const numArray = [5, 3, 8, 1, 2];
const strArray = ["banana", "apple", "cherry", "date"];

// 1. Sort an array of numbers in ascending order
const sortedNumArray = numArray.sort((a, b) => a - b);
console.log('1. Sorted Number Array (Ascending):', sortedNumArray); // Output: [1, 2, 3, 5, 8]

// 2. Sort an array of strings in alphabetical order
const sortedStrArray = strArray.sort();
console.log('2. Sorted String Array (Alphabetical):', sortedStrArray); // Output: ["apple", "banana", "cherry", "date"]

// 3. Reverse the sorted array of numbers
const reversedNumArray = sortedNumArray.reverse();
console.log('3. Reversed Sorted Number Array:', reversedNumArray); // Output: [8, 5, 3, 2, 1]

// 4. Reverse the sorted array of strings
const reversedStrArray = sortedStrArray.reverse();
console.log('4. Reversed Sorted String Array:', reversedStrArray); // Output: ["date", "cherry", "banana", "apple"]
content_copyCOPY