break array of objects into separate arrays based on a property

JavascriptJqueryArraysObjectunderscore.js

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

This is an easy job for Array.reduce(...):

function groupBy(arr, property) {
  return arr.reduce(function(memo, x) {
    if (!memo[x[property]]) { memo[x[property]] = []; }
    memo[x[property]].push(x);
    return memo;
  }, {});
}

var o = groupBy(arr, 'type'); // => {orange:[...], banana:[...]}
o.orange; // => [{"type":"orange","title":"First"},{"type":"orange","title":"Second"}]
o.banana; // => [{"type":"banana","title":"Third"},{"type":"banana","title":"Fourth"}]

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:

function groupBy2(xs, prop) {
  var grouped = {};
  for (var i=0; i<xs.length; i++) {
    var p = xs[i][prop];
    if (!grouped[p]) { grouped[p] = []; }
    grouped[p].push(xs[i]);
  }
  return grouped;
}

Solution 2 - Javascript

> JQuery and Underscore are both options to use.

Underscore's groupBy does exactly what you need.

_.groupBy(arr, "type")

Solution 3 - Javascript

This assumes an array of objects:

function groupBy(array, property) {
    var hash = {};
    for (var i = 0; i < array.length; i++) {
        if (!hash[array[i][property]]) hash[array[i][property]] = [];
        hash[array[i][property]].push(array[i]);
    }
    return hash;
}

groupBy(arr,'type')  // Object {orange: Array[2], banana: Array[2]}
groupBy(arr,'title') // Object {First: Array[1], Second: Array[1], Third: Array[1], Fourth: Array[1]}

Solution 4 - Javascript

Just build a dictionary which holds the objects based on their title. You could do it like this:

js

var arr = [
{type:"orange", title:"First"},
 {type:"orange", title:"Second"},
 {type:"banana", title:"Third"},
 {type:"banana", title:"Fourth"}
];
var sorted = {};
for( var i = 0, max = arr.length; i < max ; i++ ){
 if( sorted[arr[i].type] == undefined ){
  sorted[arr[i].type] = [];
 }
 sorted[arr[i].type].push(arr[i]);
}
console.log(sorted["orange"]);
console.log(sorted["banana"]);

jsfiddle demo: http://jsfiddle.net/YJnM6/

Solution 5 - Javascript

ES6 solution:

function groupBy(arr, property) {
  return arr.reduce((acc, cur) => {
    acc[cur[property]] = [...acc[cur[property]] || [], cur];
    return acc;
  }, {});
}

or completely ES6fy:

const groupBy = (arr, property) => {
    return arr.reduce((acc, cur) => {
      acc[cur[property]] = [...acc[cur[property]] || [], cur];
      return acc;
    }, {});
}

I hope it helps!

Solution 6 - Javascript

Typescript version.

/**
* Group object array by property
 * Example, groupBy(array, ( x: Props ) => x.id );
 * @param array
 * @param property
 */
export const groupBy = <T>(array: Array<T>, property: (x: T) => string): { [key: string]: Array<T> } =>
  array.reduce((memo: { [key: string]: Array<T> }, x: T) => {
    if (!memo[property(x)]) {
      memo[property(x)] = [];
    }
    memo[property(x)].push(x);
    return memo;
  }, {});

export default groupBy;

Solution 7 - Javascript

You can also use https://lodash.com/docs/4.17.15#groupBy

It will serve your purpose

Solution 8 - Javascript

Little tweak to @Watchmaker's answer to return array instead of object.:

function groupBy(arr, key) {
  return arr.reduce((acc, cur) => {
    acc[cur[key]] = [...acc[cur[key]] || [], cur];
    return acc;
  }, []).filter(Boolean);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEvanView Question on Stackoverflow
Solution 1 - JavascriptmaericsView Answer on Stackoverflow
Solution 2 - JavascriptBergiView Answer on Stackoverflow
Solution 3 - JavascriptShmiddtyView Answer on Stackoverflow
Solution 4 - JavascriptTravis JView Answer on Stackoverflow
Solution 5 - JavascriptWatchmakerView Answer on Stackoverflow
Solution 6 - JavascriptdenolssonView Answer on Stackoverflow
Solution 7 - JavascriptDoomed93View Answer on Stackoverflow
Solution 8 - JavascriptGopal MishraView Answer on Stackoverflow