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.

Comments

  1. User Avatar
    adebiyi adedotun
    Permalink to comment#

    Nice and considering the ways data can exist. But can’t we just convert everything to either all lowercase or uppercase then sort?

Leave a Comment

Posting Code!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag