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

var arr = [

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

];

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

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

阅读 8.8k
评论 更新于 2016-04-15
    6 个回答
    arr.reduce(function (pre, current, index) {
      pre[current.city] = pre[current.city] || []
      pre[current.city].push(current.location)
      return pre
    }, {})

    结果

    Object {上海: Array[2], 北京: Array[2], 苏州: Array[1]}
    评论 赞赏 2016-04-15