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.
This assumes an array of objects:
Underscore's
groupBy
does exactly what you need.Typescript version.
Just build a dictionary which holds the objects based on their title. You could do it like this:
js
jsfiddle demo: http://jsfiddle.net/YJnM6/
This is an easy job for
Array.reduce(...)
:Of course, if your target browser(s) do not support ECMAScript 262 5th edition then you'll have to implement "reduce" by yourself, or use a polyfill library, or choose another answer.
[Update] Here's a solution that should work with any version of JavaScript: