Sort Demo
Sort Demo
by Shrikrishna Gupta
JavaScript
let numbers = [0, 1, 2, 3, 10, 20, 30];
numbers.sort((a, b) => {
if (a > b) return -1;
if (a < b) return 1;
return 0;
});
console.log(numbers);
numbers.sort((a, b) => a - b);
console.log("Numbers in Asecnding Order : "+ numbers);
let animals = [
'cat', 'dog', 'elephant', 'bee', 'ant'
];
animals.sort((a, b) => {
if (a > b)
return -1;
if (a < b)
return 1;
return 0;
});
animals.sort((a,b) => {if(a > b) return -1 ; if(a < b) return 1; return 0});
console.log("Animals list sorted in Descending Order : " + animals);
// sorting array with mixed cases
let mixedCaseAnimals = [
'Cat', 'dog', 'Elephant', 'bee', 'ant'
];
mixedCaseAnimals.sort((a,b)=> {
let x = a.toUpperCase(),
y = b.toUpperCase();
return x==y ? 0 : x > y ? 1 : -1;
});
console.log("Mixed Animals list sorted in Descending Order : " + mixedCaseAnimals);
let animaux = ['zèbre', 'abeille', 'écureuil', 'chat'];
animaux.sort();
console.log("Locale Animals list sorted in Descending Order : " + animaux);
animaux.sort(function (a, b) {
return a.localeCompare(b);
});
console.log("Actual Locale Animals list sorted in Descending Order : " + animaux);
let employees = [
{name: 'John', salary: 90000, hireDate: "July 1, 2010"},
{name: 'David', salary: 75000, hireDate: "August 15, 2009"},
{name: 'Ana', salary: 80000, hireDate: "December 12, 2011"}
];
// sort by salary
employees.sort(function (x, y) {
return x.salary - y.salary;
});
console.table(employees);