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

var arr = [

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

];

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

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

6 个回答
• 85
``````// 获取 {} 结构
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;
}, [])
};``````
``````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]}``
• 5.6k

``````var cities = {};

for (var i = 0; i < arr.length; i++) {
if (cities[arr[i].city]) {
cities[arr[i].city].push(arr[i].location)
}
else {
cities[arr[i].city] = [arr[i].location]
}
}``````
• 2.2k
``````var cities = {};
arr.forEach(function(item, index, array) {
cities[item.city] = cities[item.city] || [];
cities[item.city].push(item);
});
``````

``````function getCityData(data){
var res={};
for(var i=0;i<data.length;i++){
var d=data[i];
var city=d['city'];
res[city]=res[city]||[];
res[city].push(d);
}
//
return res;
}
``````

``````function search(str) {
var res = [];
for(var i in arr) {
if (arr[i].city == str) {
res.push(arr[i]);
}
}
return res;
}

console.log(search("上海"));``````