Skip to content

Instantly share code, notes, and snippets.

@jcready
Last active December 10, 2015 08:38
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 jcready/4409396 to your computer and use it in GitHub Desktop.
Save jcready/4409396 to your computer and use it in GitHub Desktop.
function map(collection, callback, thisArg) {
var index = -1,
length = collection ? collection.length : 0,
result = isArray(collection) ? Array(length) : {};
callback = createCallback(callback, thisArg);
if (isArray(result)) {
while (++index < length) {
result[index] = callback(collection[index], index, collection);
}
} else {
each(collection, function(value, key, collection) {
result[key] = callback(value, key, collection);
});
}
return result;
}
var fruitList = [
{ id:1, name:'lime', color:'green', size:'small' },
{ id:2, name:'banana', color:'yellow', size:'large' },
{ id:3, name:'lemon', color:'yellow', size:'small' },
{ id:4, name:'papaya', color:'green', size:'large' },
{ id:5, name:'kiwi', color:'green', size:'small' },
{ id:6, name:'apple', color:'green', size:'small' },
{ id:7, name:'pear', color:'yellow', size:'small' },
{ id:8, name:'grape', color:'green', size:'small' },
{ id:9, name:'mango', color:'yellow', size:'large' },
{ id:10, name:'honeydew', color:'green', size:'large' }
];
var fruitByColorThenSize = _.map( _.groupBy(fruitList, 'color'), function(byColor) {
return _.map( _.groupBy(byColor, 'size'), function(bySize) {
return _.object(_.pluck(bySize, 'id'), _.pluck(bySize, 'name'));
});
});
console.dir(fruitByColorThenSize);
/*{
"green":{
"large":{
"4":"papaya",
"10":"honeydew"
},
"small":{
"1":"lime",
"5":"kiwi",
"6":"apple",
"8":"grape"
}
},
"yellow":{
"large":{
"2":"banana",
"9":"mango"
},
"small":{
"3":"lemon",
"7":"pear"
}
}
}*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment