使用js写一个方法对数据分组,类似group by

在JavaScript中,可以使用Array.prototype.reduce()方法来模拟SQL中的GROUP BY功能。以下是一个简单的示例,该示例将根据对象的某个属性对数据进行分组:

function groupBy(array, key) {
    return array.reduce((result, currentValue) => {
        // 如果结果对象中还没有当前key对应的组,则创建一个新组
        if (!result[currentValue[key]]) {
            result[currentValue[key]] = [];
        }
        // 将当前元素添加到其对应的组中
        result[currentValue[key]].push(currentValue);
        return result;
    }, {});
}

// 示例数据
const data = [
    { name: 'Alice', age: 25, city: 'New York' },
    { name: 'Bob', age: 30, city: 'Los Angeles' },
    { name: 'Charlie', age: 25, city: 'Chicago' },
    { name: 'David', age: 30, city: 'New York' },
    { name: 'Eva', age: 25, city: 'Los Angeles' }
];

// 使用groupBy函数按年龄分组
const groupedByAge = groupBy(data, 'age');
console.log(groupedByAge);
// 输出:
// {
//     '25': [
//         { name: 'Alice', age: 25, city: 'New York' },
//         { name: 'Charlie', age: 25, city: 'Chicago' },
//         { name: 'Eva', age: 25, city: 'Los Angeles' }
//     ],
//     '30': [
//         { name: 'Bob', age: 30, city: 'Los Angeles' },
//         { name: 'David', age: 30, city: 'New York' }
//     ]
// }

在这个示例中,groupBy函数接受一个数组和一个键名作为参数。它使用reduce()方法遍历数组中的每个元素,并根据元素的指定键名将其分组。最后,它返回一个对象,其中每个键都对应一个组,并且该键的值是包含在该组中的所有元素的数组。

posted @ 2024-12-30 09:15  王铁柱6  阅读(164)  评论(0)    收藏  举报