Skip to content

Instantly share code, notes, and snippets.

@XoseLluis
Last active January 26, 2023 20:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XoseLluis/bc11eed02e0f44906b5fdbb3fc18773d to your computer and use it in GitHub Desktop.
Save XoseLluis/bc11eed02e0f44906b5fdbb3fc18773d to your computer and use it in GitHub Desktop.
Sort Array by Multiple Criteria
// Factory Function to combine multiple sort criteria
// receives functions representing sorting criteria
// returns a new function that applies these criteria
function sortByMultipleCriteriaFactory(...sortFuncs){
return (it1, it2) => {
for (sort of sortFuncs){
let res = sort(it1, it2);
if (res !== 0){
//for this criteria items are not equal (in sorting terms) so no more criteria to apply
return res;
}
}
return res;
};
}
let sortByPopulation = (it1, it2) => {
return (it1.population > it2.population)
? -1
: (it1.population < it2.population)
? 1
: 0;
};
let sortByName = (it1, it2) => {
return (it1.name > it2.name)
? -1
: (it1.name < it2.name)
? 1
: 0;
};
let cities = [
{
name: "Palermo",
population: 500000
},
{
name: "Paris",
population: 12000000
},
{
name: "Bilbao",
population: 500000
},
{
name: "Xixon",
population: 270000
},
{
name: "Toulouse",
population: 500000
},
{
name: "Bologne",
population: 500000
}
];
let sortByPopulationAndName = sortByMultipleCriteriaFactory(sortByPopulation, sortByName);
console.log("before: " + cities.map(city => city.name).join("\n"));
cities.sort(sortByPopulationAndName);
console.log("after: " + cities.map(city => city.name).join("\n"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment