Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  152] [ 6]  / answers: 1 / hits: 82376  / 12 Years ago, mon, february 4, 2013, 12:00:00

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 which have 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.


More From » jquery

 Answers
11

JQuery and Underscore are both options to use.




Underscore's groupBy does exactly what you need.



_.groupBy(arr, type)

[#80421] Sunday, February 3, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryderalfonsos

Total Points: 655
Total Questions: 88
Total Answers: 91

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
ryderalfonsos questions
Mon, Sep 9, 19, 00:00, 5 Years ago
Wed, Feb 13, 19, 00:00, 5 Years ago
Tue, Feb 12, 19, 00:00, 5 Years ago
Fri, Dec 28, 18, 00:00, 6 Years ago
;