1

I have an array of objects that all contain a property snail.

I'd like to mutate this array into an array of arrays, with each element array containing objects that have a common property snail

It is very similar to lodash _.partition, except it needs to happen an indeterminate number of times, recursively, and be on a flat level and not deeply nested.

Thank you for any guidance.

Here is a sample data structure: [ { hi: "bungalo" }, { hi: 'bodego' }, { hi: 'bodego' }, { hi: 'pet rock' } ]

[ [ { snail: 'big' }, { snail: 'big' } ], [ {snail: 'small' }, {snail: 'small'} ] ]

9
  • Ah it helps to write it out sometimes - I could use _.flatten to solve the problem of nesting. But I still need to write my first recursive function! Commented Jan 12, 2016 at 5:43
  • It would be useful to post a sample of the data structure, it's pretty vague as it stands. Commented Jan 12, 2016 at 5:45
  • Its super simple. [ { hi: "bungalo" }, { hi: 'bodego' }, { hi: 'bodego' }, { hi: 'pet rock' } ] Commented Jan 12, 2016 at 5:46
  • Question not clear... what do you expect as output? And why do you need to mutate? Commented Jan 12, 2016 at 5:52
  • 2
    with respect to the sample data structure can you also post the sample output expected? I am still confused about your question. Commented Jan 12, 2016 at 5:54

2 Answers 2

1

I've played a little bit and created the following snippet which does what you're looking for in two different ways, the second one being more elegant I think:

var data = [ { snail: "bungalo", i: 1 }, { snail: 'bodego', i: 2 }, { snail: 'bodego', i: 3 }, { snail: 'pet rock', i: 4 }, { snail: "bungalo", i: 5 } ];

var multiPartitioned = _(data).uniq('snail').pluck('snail').map(function(snail) {
  return _.filter(data, 'snail', snail);
}).value();

var multiPartitionedMoreElegant = _(data).groupBy('snail').values().value();

console.log(multiPartitioned);
console.log(multiPartitionedMoreElegant);

You can see this example on CodePen: http://codepen.io/NicBright/pen/VeWXpj?editors=001

Regards, Nicolas

Sign up to request clarification or add additional context in comments.

1 Comment

ah, group by! that did it. I didn't think I needed recursion at first, but didn't see this group by. Obviously need to get more familiar with lodash chaining & .value().
1

What about the dead simple:

bysnail = {};
objects.forEach(function(x){
    (bysnail[x.snail] || (bysnail[x.snail] = [])).push(x);
});

?

The output is an object mapping snail values to the list of objects with that value.

1 Comment

That works, except for this application I need an array inside an array for the ordering in ng-repeats

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.