Skip to content
Advertisement

How do I split an array of objects into multiple arrays of objects while filtering for duplicates?

Ok, tall order I know.

So here’s my situation, say I have the array of objects below

JavaScript

I would like for this to be changed to

[{name: bar1, label: bar1}, {name: bar4, label: bar4},{name: bar7, label: bar7}]

[{name: bar2, label: bar2}, {name: bar5, label: bar5},{name: bar8, label: bar8}]

[{name: bar3, label: bar3}, {name: bar6, label: bar6}]

I have found the below from another thread that splits AoO to an object of Arrays.

JavaScript

But it does not filter for duplicates and does not format the data the way I labeled above, and I could not figure out how the function above is working. For duplicates I opted to use the _.uniq from lodash on each individual element of result but was stuck on the ‘name’ and ‘label’ formatting, so I thought I would ask much more experienced programmers than myself if there may be a way to incorporate all this into 1 function.

Advertisement

Answer

You can just add check whether the array has the element before pushing it to the array, by changing this:

JavaScript

to this:

JavaScript

JavaScript

If you wish to flatten the result to be array of arrays, you can loop through entries of the previous result and push it into the new array

JavaScript

I know that this seems inefficient, but I’m sure this is worth to try.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement