An array:
let fruits = [`bananas`, `Apples`, `Oranges`];
You can sort of alphabetize that as easy as:
fruits.sort();
But notice the inconsistent casing in the array… uppercase characters will all be sorted before lowercase characters (weirdly enough) so it’ll be a little more complicated:
let fruits = [`bananas`, `Apples`, `Oranges`];
fruits.sort((a, b) => {
return a.toLowerCase().localeCompare(b.toLowerCase());
})
console.log(fruits);
// ["Apples", "bananas", "Oranges"]
Array of Objects
Things get trickier still if what you are trying to sort is nested within objects. Easily could be the case working with a JSON API.
let fruits = [
{
fruit: `Bananas`
},
{
fruit: `apples`
},
{
fruit: `Oranges`
}
];
We could make a custom sorting function for this, but one slight step further is to make a more generic function that takes the key to sort by as a param.
const propComparator = (propName) =>
(a, b) => a[propName].toLowerCase() == b[propName].toLowerCase() ? 0 : a[propName].toLowerCase() < b[propName].toLowerCase() ? -1 : 1
So now we can use it to sort:
fruits.sort(propComparator(`fruit`));
console.log(fruits);
/*
[
{fruit: "apples"},
{fruit: "Bananas"},
{fruit: "Oranges"}
]
*/
Just an Object
If we just have an object…
let fruits = {
Bananas: true,
apples: false,
Oranges: true
};
We still need to downcase those keys, but we can sort an array of the keys and then make a new object from that newly sorted array of keys.
let sortedFruits = {};
Object.keys(fruits).sort((a, b) => {
return a.toLowerCase().localeCompare(b.toLowerCase());
}).forEach(function(key) {
sortedFruits[key] = fruits[key];
});
console.log(sortedFruits);
/*
{
apples: false,
Bananas: true,
Oranges: true
}
*/
Array of Objects to sort on Key
let fruits = [
{
Bananas: true
},
{
Apples: false
},
{
oranges: true
}
];
This is probably the trickiest of them all, but there should be enough information above to sort it out. Get it.
Live Code
See the Pen Alphabetizing Arrays by Chris Coyier (@chriscoyier) on CodePen.
Nice and considering the ways data can exist. But can’t we just convert everything to either all lowercase or uppercase then sort?
I’ve previously had the following as a technical test for a job, but I’am still curious as to how one would approach or solve this:
const newCandidates = [
{ name: “Kerrie”, skills: [“JavaScript”, “Docker”, “Ruby”] },
{ name: “Mario”, skills: [“Python”, “AWS”] },
{ name: “Jacquline”, skills: [“JavaScript”, “Azure”] },
{ name: “Kathy”, skills: [“JavaScript”, “Java”] },
{ name: “Anna”, skills: [“JavaScript”, “AWS”] },
{ name: “Matt”, skills: [“PHP”, “AWS”] },
{ name: “Matt”, skills: [“PHP”, “.Net”, “Docker”] },
];
and the function:
function filterCandidateBySkill(candidates, skill) {}
sorts by which object has the skills JavaScript first and then by how other skills they have, high to low.
I.E:
Kerrie first, others with JavaScript can be in any order