Created
October 28, 2014 09:36
-
-
Save miraculixx/3eb9d2f2d64e5567b8a1 to your computer and use it in GitHub Desktop.
transform a list of names into an alphabet-keyed dictionary.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm inclined to think there must a more straight forward way using
_.map/_.reduce
, anyone?