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

7.7k 次浏览

var arr = [

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

];

arr按city分组的方法，谢谢！

[
{city:"",location:[]}
]

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]}``

推荐答案

``````// 获取 {} 结构
const mapCityLoction = function(arr) {
let cities = {};
let locations = cities[address.city] || [];
})
return cities;
}

// forEach 获取 [ {city: , location}] 结构
const mapCityLoction_new = function() {
let newArr = [];
let index = -1;
index = j;
return true;
}
});
newArr.push({
});
} else {
}
});
return newArr;
};

// reduce 获取 [ {city: , location}] 结构
const mapCityLoction_lastest = function() {
return arr.reduce( (prev, current) => {
let index = -1;
index = i;
return true;
}
});
if (index > -1) {
prev[index].location.push(current.location);
} else {
prev.push({
city: current.city,
location: [current.location]
});
}
return prev;
}, [])
};``````