JavaScript Array Sort:
Array sort():
- The sort() method sorts an array alphabetically.
example:
const names = ["sam","ram","john"];
names.sort();
console.log(names);
output:
["sam","ram","john"]
Array reverse():
- The reverse() method reverses the elements in an array.
example:
const names1 = ["sam","ram","john"];
names1.reverse();
console.log(names1);
output:
["john", "ram", "sam"]
- By combining sort() and reverse(), you can sort an array in descending order.
example:
const names2 = ["sam", "ram", "john", "kavi"];
names2.sort();
names2.reverse();
console.log(names2);
output:
["sam","ram","kavi", "john"]
Array toSorted():
- The toSorted() method as a safe way to sort an array without altering the original array.
- The difference between toSorted() and sort() is that the first method creates a new array, keeping the original array unchanged, while the last method alters the original array.
example:
const months = ["Jan", "Feb", "Mar", "Apr"];
const sorted = months.toSorted();
console.log(sorted);
console.log(months);
output:
[ "Apr", "Feb", "Jan", "Mar" ]
[ "Jan", "Feb", "Mar", "Apr" ]
Array toReversed():
- The toReversed() method as a safe way to reverse an array without altering the original array.
- The difference between toReversed() and reverse() is that the first method creates a new array, keeping the original array unchanged, while the last method alters the original array.
example:
const months1 = ["Jan", "Feb", "Mar", "Apr"];
const reversed = months1.toReversed();
console.log(reversed);
console.log(months1);
output:
[ "Apr", "Mar", "Feb", "Jan" ]
[ "Jan", "Feb", "Mar", "Apr" ]
2.Numeric Sort:
- The sort() function sorts values as strings.
example:
const points = [40, 100, 1, 5, 25, 10];
console.log(points.sort(function (a, b) { return a - b }));
console.log(points);
output:
[ 1, 5, 10, 25, 40, 100 ]
[ 1, 5, 10, 25, 40, 100 ]
Random Sort:
(TO BE DISCUSSED)
Math.min():
- You can use Math.min.apply to find the lowest number in an array.
example:
const points2 = [40, 100, 1, 5, 25, 10];
function myArrayMin(arr) {
return Math.min.apply(null, arr);
}
const minimum = myArrayMin(points2);
console.log(minimum);
console.log(points2);
output:
1
[ 40, 100, 1, 5, 25, 10 ]
Math.max():
You can use Math.max.apply to find the highest number in an array.
example:
const points3 = [40, 100, 1, 5, 25, 10];
function myArrayMax(array) {
return Math.max.apply(null, array);
}
const maximum = myArrayMax(points3);
console.log(maximum);
console.log(points3);
output:
100
[ 40, 100, 1, 5, 25, 10 ]
Ref: W3 Schools
Top comments (0)