break array of objects into separate arrays based on a property

后端 未结 7 1177
太阳男子
太阳男子 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: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/

提交回复
热议问题