xxxxxxxxxx
numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort
xxxxxxxxxx
var names = ["Peter", "Emma", "Jack", "Mia", "Eric"];
names.sort(); // ["Emma", "Eric", "Jack", "Mia", "Peter"]
var objs = [
{name: "Peter", age: 35},
{name: "Emma", age: 21},
{name: "Jack", age: 53}
];
objs.sort(function(a, b) {
return a.age - b.age;
}); // Sort by age (lowest first)
xxxxxxxxxx
numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort
xxxxxxxxxx
//Higher order function for sorting
numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){
return a - b
});
////HOF/////
numArray.sort(function(a, b){
return a - b
});
//output >> [1 ,5 , 10 ,25 ,40 ,100]
xxxxxxxxxx
homes.sort(function(a, b) {
return parseFloat(a.price) - parseFloat(b.price);
});
xxxxxxxxxx
const items = [
{ name: "Edward", value: 21 },
{ name: "Sharpe", value: 37 },
{ name: "And", value: 45 },
{ name: "The", value: -12 },
{ name: "Magnetic", value: 13 },
{ name: "Zeros", value: 37 },
];
items.sort(function (a, b) {
if (a.name > b.name) {
return 1;
}
if (a.name < b.name) {
return -1;
}
// a must be equal to b
return 0;
});
xxxxxxxxxx
// Ascending sort
items.sort((a, b) => a.value - b.value);
// Descending sort
items.sort((a, b) => b.value - a.value);
xxxxxxxxxx
// student array
let students = ['John', 'Jane', 'Mary', 'Mark', 'Bob'];
// sort the array in ascending order
students.sort();
// ? result = ['Bob', 'Jane', 'John', 'Mark', 'Mary']
// sort the array in descending order
students.sort().reverse();
// ? result = ['Mary', 'Mark', 'John', 'Jane', 'Bob']
xxxxxxxxxx
homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));