JavaScript中的groupBy
函数用于根据指定的键对数组进行分组。它将数组中具有相同键的元素归类到一个新的对象中。以下是一个示例代码:
function groupBy(arr, key) {
return arr.reduce((acc, obj) => {
const groupKey = obj[key];
if (!acc[groupKey]) {
acc[groupKey] = [];
}
acc[groupKey].push(obj);
return acc;
}, {});
}
const data = [
{ name: 'Alice', age: 25, city: 'New York' },
{ name: 'Bob', age: 30, city: 'London' },
{ name: 'Charlie', age: 35, city: 'New York' },
{ name: 'Dave', age: 40, city: 'London' },
];
const groupedData = groupBy(data, 'city');
console.log(groupedData);
上述代码将根据city
键将数据分组,并将结果打印到控制台。输出结果如下:
{
'New York': [
{ name: 'Alice', age: 25, city: 'New York' },
{ name: 'Charlie', age: 35, city: 'New York' }
],
'London': [
{ name: 'Bob', age: 30, city: 'London' },
{ name: 'Dave', age: 40, city: 'London' }
]
}
这个函数非常有用,特别是在需要对数据进行分组和聚合的情况下,例如统计每个城市的人数或计算每个城市的平均年龄等。
在表格中打印分组后的数据,可以使用HTML和JavaScript来实现。以下是一个简单的示例:
<!DOCTYPE html>
<html>
<head>
<title>GroupBy Example</title>
<style>
table {
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 5px;
}
</style>
</head>
<body>
<table id="groupedTable">
<thead>
<tr>
<th>City</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
function groupBy(arr, key) {
return arr.reduce((acc, obj) => {
const groupKey = obj[key];
if (!acc[groupKey]) {
acc[groupKey] = [];
}
acc[groupKey].push(obj);
return acc;
}, {});
}
const data = [
{ name: 'Alice', age: 25, city: 'New York' },
{ name: 'Bob', age: 30, city: 'London' },
{ name: 'Charlie', age: 35, city: 'New York' },
{ name: 'Dave', age: 40, city: 'London' },
];
const groupedData = groupBy(data, 'city');
const tableBody = document.querySelector('#groupedTable tbody');
for (const city in groupedData) {
const cityData = groupedData[city];
cityData.forEach((obj) => {
const row = document.createElement('tr');
const cityCell = document.createElement('td');
const nameCell = document.createElement('td');
const ageCell = document.createElement('td');
cityCell.textContent = city;
nameCell.textContent = obj.name;
ageCell.textContent = obj.age;
row.appendChild(cityCell);
row.appendChild(nameCell);
row.appendChild(ageCell);
tableBody.appendChild(row);
});
}
</script>
</body>
</html>
上述代码将根据city
键将数据分组,并将分组后的数据打印到表格中。每个分组的城市名称只在第一行显示,后续行为空。输出结果如下:
City Name Age
New York Alice 25
Charlie 35
London Bob 30
Dave 40
这个示例使用了HTML的表格元素和JavaScript的DOM操作来动态创建表格行和单元格,并将数据填充到相应的单元格中。
领取专属 10元无门槛券
手把手带您无忧上云