Create a script for sorting the given array in decreasing order. const array = [5, 10,…
- User
Create a script for sorting the given array in decreasing order. const array = [5, 10, 8, 6, 4, 9, 2]
Assistant
Create a script for sorting the given array in decreasing order. const array = [5, 10, 8, 6, 4, 9, 2]
I'm choosing JavaScript's built-in sort() method with a custom comparator function because:
For descending order, the comparator (a, b) => b - a:
b > a → b comes firsta > b → a comes firstI'll demonstrate both in-place sorting (mutates original) and non-mutating approach (preserves original), as the choice depends on broader application context.
// ============================================
// Array Sorting Script - Descending Order
// ============================================
const array = [5, 10, 8, 6, 4, 9, 2];
// --------------------------------------------
// Solution 1: In-place sort (mutates original)
// --------------------------------------------
function sortDescendingInPlace(arr) {
return arr.sort((a, b) => b - a);
}
// --------------------------------------------
// Solution 2: Non-mutating (preserves original)
// --------------------------------------------
function sortDescendingImmutable(arr) {
return [...arr].sort((a, b) => b - a);
}
// --------------------------------------------
// Execution
// --------------------------------------------
console.log("Original array:", array);
// Method 1: In-place
sortDescendingInPlace(array);
console.log("Sorted (descending):", array);
// --------------------------------------------
// Alternative: If you need to preserve original
// --------------------------------------------
const originalCopy = [5, 10, 8, 6, 4, 9, 2];
const sortedCopy = sortDescendingImmutable(originalCopy);
console.log("\n--- Immutable Approach ---");
console.log("Original preserved:", originalCopy);
console.log("New sorted array:", sortedCopy);
// --------------------------------------------
// Expected Output:
// Original array: [5, 10, 8, 6, 4, 9, 2]
// Sorted (descending): [10, 9, 8, 6, 5, 4, 2]
//
// --- Immutable Approach ---
// Original preserved: [5, 10, 8, 6, 4, 9, 2]
// New sorted array: [10, 9, 8, 6, 5, 4, 2]
// --------------------------------------------
| Approach | Use Case | Time Complexity |
|---|---|---|
sort((a,b) => b-a) | Most production code | O(n log n) |
[...arr].sort() | When immutability needed | O(n log n) |
For production: Use the immutable approach unless you explicitly want to modify the original array. This prevents unintended side effects in larger codebases.