break array of objects into separate arrays based on a property

后端 未结 7 1139
太阳男子
太阳男子 2020-12-01 07:10

Say I have an array like this:

var arr = [
    {type:\"orange\", title:\"First\"},
    {type:\"orange\", title:\"Second\"},
    {type:\"banana\", title:\"Thi         


        
相关标签:
7条回答
  • 2020-12-01 07:38

    JQuery and Underscore are both options to use.

    Underscore's groupBy does exactly what you need.

    _.groupBy(arr, "type")
    
    0 讨论(0)
  • 2020-12-01 07:43

    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!

    0 讨论(0)
  • 2020-12-01 07:47

    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]}
    
    0 讨论(0)
  • 2020-12-01 07:47

    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;
    
    0 讨论(0)
  • 2020-12-01 07:50

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

    It will serve your purpose

    0 讨论(0)
  • 2020-12-01 07:52

    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/

    0 讨论(0)
提交回复
热议问题