Home / Code Snippets / JavaScript / Alphabetizing Arrays, Objects, and Arrays of Objects

Alphabetizing Arrays, Objects, and Arrays of Objects

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.