var fruits = [
{ fruit: "apple", color: "red" },
{ fruit: "orange", color: "orange" },
{ fruit: "cherry", color: "red" },
{ fruit: "grape", color: "green" },
{ fruit: "strawberry", color: "red" },
{ fruit: "lemon", color: "yellow" },
{ fruit: "peach", color: "yellow" },
{ fruit: "kiwi", color: "green" },
{ fruit: "lime", color: "green" }
];
// This actually ended up taking me about an hour (which is a LONG time for one simple
// sorting function). I had to think about the logic a lot harder than I should have.
// Anyway, it turns out that before even checking the color of the fruit, it's important
// to first check if the colors are the same. If (and only if) they are, then go on to
// check which fruit should come first.
sortedFruits = fruits.sort(function compare (a, b) {
if (a.color === b.color){ // <-- This part is what took me the longest to realize.
if (a.fruit < b.fruit)
return -1;
if (a.fruit > b.fruit)
return 1;
return 0;
}
if (a.color < b.color)
return -1;
if (a.color > b.color)
return 1;
return 0;
});