Sort and Reverse Array Elements
In this step, you'll learn how to use the sort()
and reverse()
methods to manipulate array elements in JavaScript. These methods provide simple ways to organize and reorder array contents.
Create a new file called array-sort-reverse.js
in the ~/project
directory and add the following code:
// Create arrays for sorting demonstration
let numbers = [5, 2, 9, 1, 7];
let fruits = ["banana", "apple", "cherry", "date"];
// Default sorting (lexicographic for strings, ascending for numbers)
console.log("Original numbers:", numbers);
numbers.sort();
console.log("Default sort:", numbers);
// Numeric sorting requires a comparison function
numbers = [5, 2, 9, 1, 7];
numbers.sort((a, b) => a - b);
console.log("Numeric sort:", numbers);
// Reverse sorting
console.log("\nOriginal fruits:", fruits);
fruits.sort().reverse();
console.log("Sorted and reversed:", fruits);
// Reverse an array without sorting
let colors = ["red", "green", "blue", "yellow"];
console.log("\nOriginal colors:", colors);
colors.reverse();
console.log("Reversed colors:", colors);
Now, run the script to see the results:
node ~/project/array-sort-reverse.js
Example output:
Original numbers: [ 5, 2, 9, 1, 7 ]
Default sort: [ 1, 2, 5, 7, 9 ]
Numeric sort: [ 1, 2, 5, 7, 9 ]
Original fruits: [ 'banana', 'apple', 'cherry', 'date' ]
Sorted and reversed: [ 'date', 'cherry', 'banana', 'apple' ]
Original colors: [ 'red', 'green', 'blue', 'yellow' ]
Reversed colors: [ 'yellow', 'blue', 'green', 'red' ]
Key points about sort()
and reverse()
:
sort()
modifies the original array
- Default
sort()
converts elements to strings and sorts lexicographically
- Use a comparison function for numeric or custom sorting
reverse()
reverses the order of elements in the array
- Both methods work in-place, changing the original array