2

var arr = [

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

];

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

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

2016-04-15 提问

查看全部 6 个回答

0

在处理这种结构的时候,感觉就有点给自己找麻烦。
自己都觉得处理起来比较麻烦的时候,就可以思考一下有什么方法可以更好的解决,何必写程序来难为自己呢。

以上内容为玩笑,勿介意。

下面提供一种处理方案:

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;
}

只是提供一种思路,非最终解决方案!

推荐答案

0

已采纳
// 获取 {} 结构
const mapCityLoction = function(arr) {
    let cities = {};
    arr.forEach((address, index) => {
        let locations = cities[address.city] || [];
        locations.push(address.location);
        cities[address.city] = locations;
    })
    return cities;
}

// forEach 获取 [ {city: , location}] 结构
const mapCityLoction_new = function() {
    let newArr = [];
    arr.forEach((address, i) => {
        let index = -1;
        let alreadyExists = newArr.some((newAddress, j) => {
            if (address.city === newAddress.city) {
                index = j;
                return true;
            }
        });
        if (!alreadyExists) {
            newArr.push({
                city: address.city,
                location: [address.location]
            });
        } else {
            newArr[index].location.push(address.location);
        }
    });
    return newArr;
};

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

推广链接