求一个数组按属性分组的方法

var arr = [

{city: "上海", location: "浦东"},
{city: "上海", location: "静安"},
{city: "北京", location: "内环"},
{city: "北京", location: "五环"},
{city: "苏州", location: "苏州"},

];

arr按city分组的方法,谢谢!

返回一个数组
[
{city:"",location:[]}
]

阅读 8.6k
评论 更新于 2016-04-15
    6 个回答
    hiYoHoo
    • 2.2k
    var cities = {};
    arr.forEach(function(item, index, array) {
        cities[item.city] = cities[item.city] || [];
        cities[item.city].push(item);
    });
    
    评论 赞赏 2016-04-15