Evan Evan - 1 year ago 65
Javascript Question

break array of objects into separate arrays based on a property

Say I have an array like this:

var arr = [
{type:"orange", title:"First"},
{type:"orange", title:"Second"},
{type:"banana", title:"Third"},
{type:"banana", title:"Fourth"}

and I want this to be split up into arrays that have objects that have the same type so:

[{type:"orange", title:"First"},
{type:"orange", title:"Second"}]

[{type:"banana", title:"Third"},
{type:"banana", title:"Fourth"}]

But I want to do this generically so not having an if statement that specifies orange or banana

// not like this
for (prop in arr){
if (arr[prop] === "banana"){
//add to new array

Thoughts? JQuery and Underscore are both options to use.

Answer Source

JQuery and Underscore are both options to use.

Underscore's groupBy does exactly what you need.

_.groupBy(arr, "type")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download