Skip to content

Instantly share code, notes, and snippets.

@DevJMD
Last active July 2, 2016 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DevJMD/a8992f57af541721fcbb30aa48c5f7e4 to your computer and use it in GitHub Desktop.
Save DevJMD/a8992f57af541721fcbb30aa48c5f7e4 to your computer and use it in GitHub Desktop.
Alphabetical Ordering
let ingredients = ['Pepper', 'Apples', 'Bananas'];
function sortAlphabetical(array, reverse) {
// Regex alphabetical characters only.
const AcceptableCharacters = /^[a-zA-Z ]*$/;
// Check to see if each item starts with an alphbetical
// character. If not, then the array isn't vaild.
array.map((item) => {
const regexStringIsAlphabetitcal = AcceptableCharacters.test(item.substring(0, 1));
if (!regexStringIsAlphabetitcal) {
throw new Error(`sortAlphabetical: Cannot use ${item} to sort an array alphabetically.`);
}
});
// Compare A to B, checking if the alphabetical ordering of
// each letter for each word is correct.
array.sort((a, b) => {
let itemA = a.toLowerCase(),
itemB = b.toLowerCase();
if (itemA < itemB) return -1;
if (itemA > itemB) return 1;
});
// Reverse the ordering of the list if true.
if (reverse) array.reverse();
return array;
}
console.log(sortAlphabetical(ingredients, false));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment