开发者社区> 问答> 正文

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

var arr = [

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

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

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

展开
收起
a123456678 2016-03-11 10:21:00 1973 0
1 条回答
写回答
取消 提交回答
  • // 获取 {} 结构
    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;
        }, [])
    };
    2019-07-17 18:58:34
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
重新定义计算的边界 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载