Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Javascript Array按属性分组 #27

Open
ybning opened this issue Dec 26, 2017 · 0 comments
Open

Javascript Array按属性分组 #27

ybning opened this issue Dec 26, 2017 · 0 comments

Comments

@ybning
Copy link
Owner

ybning commented Dec 26, 2017

待分组的数组:

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

forEach实现第一种:

// 获取 {} 结构
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;
}

g1


forEach实现第二种:

// 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实现:

// 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;
    }, [])
};
  • 每种实现各有优缺点,视具体情况而择。

最后推荐一本书:深入浅出 Webpack

@ybning ybning changed the title Javascript 数组按属性分组 Javascript Array按属性分组 Dec 26, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant