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
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
homes.sort(function(a, b) {
return parseFloat(a.price) - parseFloat(b.price);
});
xxxxxxxxxx
// Ascending sort
items.sort((a, b) => a.value - b.value);
// Descending sort
items.sort((a, b) => b.value - a.value);
xxxxxxxxxx
homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
xxxxxxxxxx
//^ merge and sort arrays in JS
const array1 = [1, 2, 3, 5, 9, 10];
const array2 = [4, 8, 6, 7];
let sortedNewArray = [array1, array2];
sortedNewArray.sort(function (a, b) {
return a - b;
});
console.log(sortedNewArray);