Sorting in JavaScript

Our example demonstrates sorting in JavaScript. We’ll look at sorting for built-in types first.

// JavaScript's Array object has a built-in sort method
// that we can use for sorting various data types.

// Sorting strings
let strs = ["c", "a", "b"];
strs.sort();
console.log("Strings:", strs);

// Sorting numbers
let ints = [7, 2, 4];
ints.sort((a, b) => a - b);
console.log("Numbers:", ints);

// We can also check if an array is already sorted
function isSorted(arr) {
    return arr.every((v, i, a) => !i || a[i-1] <= v);
}

console.log("Sorted:", isSorted(ints));

To run the program, save it as sorting.js and use node:

$ node sorting.js
Strings: [ 'a', 'b', 'c' ]
Numbers: [ 2, 4, 7 ]
Sorted: true

In JavaScript, the Array.prototype.sort() method is used for sorting. By default, it sorts elements as strings. For sorting numbers, we need to provide a comparison function.

The sort() method modifies the original array. If you need to keep the original array unchanged, you can create a copy before sorting:

let sortedInts = [...ints].sort((a, b) => a - b);

JavaScript doesn’t have a built-in method to check if an array is sorted, so we implemented a custom isSorted function. This function uses the Array.prototype.every() method to check if each element is greater than or equal to the previous one.

Remember that JavaScript’s sorting is not stable by default. If you need stable sorting, consider using a library or implementing your own sorting algorithm.

This example demonstrates basic sorting in JavaScript. For more complex sorting scenarios, you might want to look into advanced techniques or use specialized libraries.