Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Reorder an array in JavaScript
Reordering an array means changing the sequence of elements within the array. JavaScript provides several built-in methods to reorder arrays, each serving different purposes.
Using sort() for Alphabetical Ordering
The sort() method sorts array elements alphabetically in ascending order by default. It modifies the original array.
Original: Telangana,Uttar Pradesh,Karnataka,Kerala,TamilNadu Sorted: Karnataka,Kerala,TamilNadu,Telangana,Uttar Pradesh
Using reverse() Method
The reverse() method reverses the order of elements in an array. The first element becomes the last, and the last becomes the first. This method modifies the original array.
Original: Vizag,Hyderabad,Bangalore,Gurgaon Reversed: Gurgaon,Bangalore,Hyderabad,Vizag
Manual Swapping with Temporary Variable
You can manually reorder specific elements by swapping their positions using a temporary variable.
Original array: 23,53,12,87,9 After swapping: 53,23,87,12,9
The Problem with sort() for Numbers
The sort() method converts elements to strings before comparing, which causes incorrect sorting for numbers:
const numbers = [12, 34, 564, 1232134]; numbers.sort(); console.log(numbers);
[12, 1232134, 34, 564]
Using Compare Functions for Numeric Sorting
To properly sort numbers, use a compare function with sort(). The compare function returns:
- Negative value: first element comes before second
- Zero: no change in order
- Positive value: second element comes before first
Syntax
// Ascending order
array.sort(function(a, b) { return a - b; });
// Descending order
array.sort(function(a, b) { return b - a; });
Example
Click buttons to reorder the array:
Ascending: 13,23,64,75,86 Descending: 86,75,64,23,13
Comparison of Methods
| Method | Use Case | Modifies Original |
|---|---|---|
sort() |
Alphabetical sorting | Yes |
sort(compare) |
Numeric sorting | Yes |
reverse() |
Reverse order | Yes |
| Manual swapping | Custom reordering | Yes |
Conclusion
JavaScript offers multiple ways to reorder arrays: sort() for alphabetical ordering, reverse() for reversing, compare functions for numeric sorting, and manual swapping for custom arrangements. Choose the method based on your specific reordering needs.
