Skip to content

Instantly share code, notes, and snippets.

@miraculixx
Created October 28, 2014 09:36
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 miraculixx/3eb9d2f2d64e5567b8a1 to your computer and use it in GitHub Desktop.
Save miraculixx/3eb9d2f2d64e5567b8a1 to your computer and use it in GitHub Desktop.
transform a list of names into an alphabet-keyed dictionary.
// transform a list of names into an alphabet-keyed dictionary.
// e.g. input is
//
// var list = ["Elsie Chambers", "Gene Keller", "Glen Hall", "Lawrence Burke", "Lenora Robbins", "Lillian Stone", "Lucy Roberson", "Mario Curry",
// "Shawn Matthews", "Terry Joseph"]
//
// asAlphabetDictionary(list) =>
// {"A":["Adrian Stanley"],"F":["Fred Houston"],"H":["Hilda Hart"],
// "I":["Irene Coleman"],"J":["Jeffery Castillo","Jon Floyd","Jonathan
// Conner"],"L":["Leon Higgins"],"N":["Nettie Jensen"],"S":["Sally
// Simon"]}
//
// by miraculixx at github
var genNames = function(count) {
var list = [];
for(var i = 0; i < count; i++) {
list.push(chance.name());
}
return list;
};
var asAlphabetDictionary = function(list, full) {
var dict = {};
if(full) {
// get alphabet A..Z
var alpha = String.fromCharCode.apply(this, _.range(65, 65+26));
_.each(alpha.split(''), function(v) {
dict[v] = new Array();
});
}
list.sort();
_.each(list, function(v, k, l) {
var letter = v.substring(0,1).toUpperCase();
if(!full && !(letter in dict)) {
dict[letter] = new Array();
}
dict[letter].push(v);
});
return dict;
};
var list = genNames(5);
var dictSmall = asAlphabetDictionary(list, false);
var dictFull = asAlphabetDictionary(list, true);
console.log(list);
console.log(JSON.stringify(dictFull));
console.log(JSON.stringify(dictSmall));
@miraculixx
Copy link
Author

I'm inclined to think there must a more straight forward way using _.map/_.reduce, anyone?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment