The JavaScript sort()
method arranges array elements alphabetically by default, treating them as strings. A custom comparison function is needed for numerical sorting, allowing you to control the sorting criteria for precise and efficient organization.
Syntax:
arr.sort(compareFunction);
Parameters:
- array: The array to be sorted.
- compareFunction (Optional): A function that defines the sort order. If omitted, the array elements are sorted based on their string Unicode code points.
Example 1: Sorting an Array of Strings
// Original array
let arr = ["Ganesh", "Ajay", "Kunal"];
console.log(arr); // Output:["Ganesh", "Ajay", "Kunal"]
// Sorting the array
console.log(arr.sort()); // Output: [ 'Ajay', 'Ganesh', 'Kunal' ]
Example 2: Sorting an Array of Numbers
// Original array
let numbers = [40, 30, 12, 25];
console.log(numbers); // Output: [40, 30, 12, 25]
// Sorting the array
numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [ 12, 25, 30, 40 ]
Bubble Sort Implementation
In addition to using the built-in sort()
method, you can implement your own sorting algorithm. Here’s an example using the Bubble Sort algorithm:
index.js
function Sortarr() {
let Data = [40, 30, 12, 25];
for (let i = 0; i < Data.length; i++) {
for (let j = 0; j < Data.length - 1; j++) {
if (Data[j] > Data[j + 1]) {
let temp = Data[j];
Data[j] = Data[j + 1];
Data[j + 1] = temp;
}
}
}
console.log(Data); // Output: [ 12, 25, 30, 40 ]
}
Sortarr();
This Bubble Sort implementation demonstrates a basic sorting technique that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
Top comments (0)