在javascript中,数组分组的核心是通过属性值作为键将元素归类,主要使用reduce或原生groupby方法实现。1. 使用reduce可灵活处理复杂逻辑,结合map或普通对象存储结果,适合多条件分组;2. array.prototype.groupby(实际为object.groupby和map.groupby)提供更简洁、语义化的分组方式,但存在浏览器兼容性限制且灵活性不如reduce;3. 分组后可通过foreach、for...of或object.entries等方法遍历结果,并对每组数据进行聚合或筛选操作,从而实现高效的数据处理。

在JavaScript中,实现数组分组的核心思路是根据某个(或多个)属性的值作为键,将原始数组中的元素归类到不同的集合中。这通常通过遍历数组,并利用
Map
Array.prototype.groupBy
对我来说,处理数组分组,
reduce
Map
假设我们有一组用户数据,想按城市分组:
const users = [
{ id: 1, name: 'Alice', city: 'New York' },
{ id: 2, name: 'Bob', city: 'London' },
{ id: 3, name: 'Charlie', city: 'New York' },
{ id: 4, name: 'David', city: 'Paris' },
{ id: 5, name: 'Eve', city: 'London' },
];
// 使用 reduce 和 Map 进行分组
const groupedByCity = users.reduce((acc, user) => {
const city = user.city;
if (!acc.has(city)) {
acc.set(city, []); // 如果这个城市还没出现过,就创建一个空数组
}
acc.get(city).push(user); // 把当前用户加到对应城市的数组里
return acc;
}, new Map()); // 初始值是一个空的 Map
console.log(groupedByCity);
/*
Map(3) {
'New York' => [ { id: 1, name: 'Alice', city: 'New York' }, { id: 3, name: 'Charlie', city: 'New York' } ],
'London' => [ { id: 2, name: 'Bob', city: 'London' }, { id: 5, name: 'Eve', city: 'London' } ],
'Paris' => [ { id: 4, name: 'David', city: 'Paris' } ]
}
*/
// 如果你更喜欢普通对象作为结果,可以这样:
const groupedByCityObject = users.reduce((acc, user) => {
const city = user.city;
acc[city] = acc[city] || []; // 如果这个城市还没出现过,就初始化一个空数组
acc[city].push(user);
return acc;
}, {}); // 初始值是一个空对象
console.log(groupedByCityObject);
/*
{
'New York': [ { id: 1, name: 'Alice', city: 'New York' }, { id: 3, name: 'Charlie', city: 'New York' } ],
'London': [ { id: 2, name: 'Bob', city: 'London' }, { id: 5, name: 'Eve', city: 'London' } ],
'Paris': [ { id: 4, name: 'David', city: 'Paris' } ]
}
*/选择
Map
Map
Array.prototype.groupBy
说实话,每次写
reduce
Array.prototype.groupBy
优势:
reduce
groupBy
Map
Object
groupBy
groupByToMap
限制:
reduce
groupBy
reduce
Array.prototype.groupBy
Array.prototype.groupByToMap
groupBy
// 假设还是上面的 users 数组
const users = [
{ id: 1, name: 'Alice', city: 'New York' },
{ id: 2, name: 'Bob', city: 'London' },
{ id: 3, name: 'Charlie', city: 'New York' },
{ id: 4, name: 'David', city: 'Paris' },
{ id: 5, name: 'Eve', city: 'London' },
];
// 按城市分组,结果是普通对象
const groupedByCityNative = Object.groupBy(users, user => user.city);
console.log(groupedByCityNative);
/*
{
'New York': [ { id: 1, name: 'Alice', city: 'New York' }, { id: 3, name: 'Charlie', city: 'New York' } ],
'London': [ { id: 2, name: 'Bob', city: 'London' }, { id: 5, name: 'Eve', city: 'London' } ],
'Paris': [ { id: 4, name: 'David', city: 'Paris' } ]
}
*/
// 如果要返回 Map
const groupedByCityNativeMap = Map.groupBy(users, user => user.city);
console.log(groupedByCityNativeMap);
/*
Map(3) {
'New York' => [ { id: 1, name: 'Alice', city: 'New York' }, { id: 3, name: 'Charlie', city: 'New York' } ],
'London' => [ { id: 2, name: 'Bob', city: 'London' }, { id: 5, name: 'Eve', city: 'London' } ],
'Paris' => [ { id: 4, name: 'David', city: 'Paris' } ]
}
*/注意,
Object.groupBy
Object
Array.prototype
Map.groupBy
Map
当分组条件变得复杂时,比如要根据年龄段、状态和部门同时分组,或者分组键需要通过计算才能得出,
reduce
举个例子,我们想把用户按“活跃状态”和“年龄段”进行分组:
const people = [
{ name: 'Anna', age: 25, status: 'active', department: 'HR' },
{ name: 'Ben', age: 35, status: 'inactive', department: 'IT' },
{ name: 'Chloe', age: 28, status: 'active', department: 'IT' },
{ name: 'Daniel', age: 40, status: 'active', department: 'HR' },
{ name: 'Ella', age: 19, status: 'active', department: 'Sales' },
{ name: 'Frank', age: 50, status: 'inactive', department: 'Sales' },
];
const groupedByStatusAndAgeRange = people.reduce((acc, person) => {
let ageRange;
if (person.age < 25) {
ageRange = 'Under 25';
} else if (person.age >= 25 && person.age <= 35) {
ageRange = '25-35';
} else {
ageRange = 'Over 35';
}
// 组合多个条件作为键
const groupKey = `${person.status}-${ageRange}`;
acc[groupKey] = acc[groupKey] || [];
acc[groupKey].push(person);
return acc;
}, {});
console.log(groupedByStatusAndAgeRange);
/*
{
'active-25-35': [ { name: 'Anna', age: 25, status: 'active', department: 'HR' }, { name: 'Chloe', age: 28, status: 'active', department: 'IT' } ],
'inactive-25-35': [ { name: 'Ben', age: 35, status: 'inactive', department: 'IT' } ],
'active-Over 35': [ { name: 'Daniel', age: 40, status: 'active', department: 'HR' } ],
'active-Under 25': [ { name: 'Ella', age: 19, status: 'active', department: 'Sales' } ],
'inactive-Over 35': [ { name: 'Frank', age: 50, status: 'inactive', department: 'Sales' } ]
}
*/这里,我们通过字符串拼接的方式创建了一个复合键。这种方法非常灵活,你可以根据业务需求,在
reduce
groupBy
groupBy
reduce
一旦数组被分组,我们得到的结果通常是一个
Map
遍历 Map
如果你的分组结果是
Map
forEach
for...of
keys()
values()
entries()
// 假设 groupedByCity 是一个 Map 对象
console.log("--- 遍历 Map 结果 ---");
groupedByCity.forEach((usersInCity, city) => {
console.log(`城市:${city},人数:${usersInCity.length}`);
// 可以在这里对 usersInCity 数组进行进一步操作,比如计算平均年龄
const totalAge = usersInCity.reduce((sum, user) => sum + user.id, 0); // 假设id代表年龄
console.log(` 总ID值 (假设年龄):${totalAge}`);
});
// 或者使用 for...of
for (const [city, usersInCity] of groupedByCity.entries()) {
console.log(`[${city}] 包含 ${usersInCity.length} 位用户。`);
}遍历普通对象类型的结果:
如果你的分组结果是普通对象,通常会使用
Object.keys()
Object.values()
Object.entries()
forEach
for...of
// 假设 groupedByCityObject 是一个普通对象
console.log("--- 遍历 普通对象 结果 ---");
Object.entries(groupedByCityObject).forEach(([city, usersInCity]) => {
console.log(`城市:${city},用户列表:`);
usersInCity.forEach(user => console.log(` - ${user.name}`));
});
// 计算每个城市的用户数量
const cityCounts = Object.keys(groupedByCityObject).map(city => ({
city: city,
count: groupedByCityObject[city].length
}));
console.log(cityCounts);
/*
[
{ city: 'New York', count: 2 },
{ city: 'London', count: 2 },
{ city: 'Paris', count: 1 }
]
*/在实际应用中,分组后的数据往往是进一步分析或展示的基础。比如,你可能需要计算每个组的平均值、总和,或者筛选出符合特定条件的组。这些操作都可以在遍历分组结果时,对每个子数组(即每个组)进行独立的处理。记住,每个组本身就是一个数组,你可以对其应用任何常规的数组方法(
Map
filter
reduce
以上就是js如何实现数组分组的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号