var companies = [
{name: "AirBnb", year: 2005},
{name: "Tesla", year: 2000},
{name: "Google", year: 1995}
];
var sortedCompanies = companies.sort(function(item1, item2) {
if (item1.year > item2.year) {
return 1;
} else {
return -1;
}
});
console.log(sortedCompanies);
// [{name: "Google", year: 1995}, {name: "Tesla", year: 2000}, {name: "AirBnb", year: 2005}]
Alternative syntax with arrow function:
var companies = [
{name: "Tesla", year: 2000},
{name: "AirBnb", year: 2005},
{name: "Google", year: 1995}
];
var sortedCompanies = companies.sort((item1, item2) => (item1.year > item2.year) ? 1 : -1);
console.log(sortedCompanies);
// [{name: "Google", year: 1995}, {name: "Tesla", year: 2000}, {name: "AirBnb", year: 2005}]
Sort array of numbers:
var nums = [-1, -5, 3, 22];
var numsSortedWrong = nums.sort(); // Sorted as strings
console.log(numsSortedWrong); // [-1, -5, 22, 3]
var numsSorted = nums.sort((item1, item2) => item1 - item2);
console.log(numsSorted); // [-5, -1, 3, 22]