Added a _.createIndex method #995

wants to merge 2 commits into


None yet
4 participants

bwiklund commented Mar 4, 2013

This is a function I use a lot, to convert an array into an object keyed off an index. I find it really useful for taking arrays from REST endpoints, and keying them off their id.

Example usage:

var array = [{foo:{bar:'baz'}},{foo:{bar:'boop'}}];
var obj = _.createIndex(array,'',true);


baz: {foo:{bar:'baz'}},
boop: {foo:{bar:'boop'}}

It takes a 'path' as a string, and splits it on ".". It can also take an array in case your parameters have dots in them.

It's third argument is a boolean for whether or not the indexes are unique. If not, it will return an object of arrays of the original elements.


kitcambridge commented Mar 4, 2013

Actually, I think your example can be refactored using _.groupBy, so that it produces a similar result:

var obj = _.groupBy(array, function(value){ return; });
// => { "baz": [{"foo": { "bar": "baz" } }], "boop": [{ "foo": { "bar": "boop" } }]}

...Though, admittedly, that only addresses one of your use cases (it doesn't support string-based lookups or unique values).

bwiklund commented Mar 4, 2013

Nice, I didn't realize that was there.

Would it be worthwhile to extend groupBy, so it takes a function OR string for the second argument? And possibly a third 'unique' argument?


braddunbar commented Mar 4, 2013

Hi @bwiklund! _.groupBy already takes a property name as a second argument (in master, at least). It does not, however, split the string on ..

bwiklund commented Mar 4, 2013

Would it be worth making a pull request with a version of groupBy that can expand the strings, and/or take an array of the nested params?


braddunbar commented Mar 4, 2013

It's been suggested before and the consensus is that a function is a better way to go about it (you can find many discussions in the issues). New pull requests are always welcome though, even if only for purposes of discussion. :)

@jashkenas jashkenas closed this Jul 6, 2013

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