const myArray = [
{ name: 'John', age: 25, gender: 'male' },
{ name: 'Jane', age: 30, gender: 'female' },
{ name: 'Bob', age: 20, gender: 'male' },
{ name: 'Alice', age: 35, gender: 'female' },
{ name: 'Tom', age: 28, gender: 'male' },
{ name: 'Cathy', age: 32, gender: 'female' }
];
function groupBy (array, property) {
return array.reduce(function (acc, obj) {
let key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
const groupedArray = groupBy(myArray, 'gender');
console.log(groupedArray);
const myArray = [
{ name: 'John', count: 25, date: '2023-06-15' },
{ name: 'Jane', count: 30, date: '2023-06-15' },
{ name: 'Alice', count: 20, date: '2023-06-15' },
{ name: 'John', count: 35, date: '2023-06-16' },
{ name: 'Jane', count: 28, date: '2023-06-16' },
{ name: 'Alice', count: 32, date: '2023-06-16' },
{ name: 'John', count: 3, date: '2023-06-17' },
{ name: 'Jane', count: 8, date: '2023-06-17' },
{ name: 'Alice', count: 6, date: '2023-06-17' },
{ name: 'John', count: 5, date: '2023-06-18' },
{ name: 'Jane', count: 17, date: '2023-06-18' },
{ name: 'Alice', count: 46, date: '2023-06-18' },
];
const result = {};
myArray.forEach(item => {
if (!result[item.name]) {
result[item.name] = {
name: item.name,
count: 0,
data: []
};
}
result[item.name].count += item.count;
result[item.name].data.push({
count: item.count,
date: item.date
});
});
const total = output.reduce((prev, current) => {
return prev + current.count;
}, 0);
output.push({
name: '合计',
count: total,
data: []
});
const dateMap = new Map();
output.forEach(item => {
item.data.forEach(dataItem => {
if (!dateMap.has(dataItem.date)) {
dateMap.set(dataItem.date, {
date: dataItem.date,
count: 0
});
}
dateMap.get(dataItem.date).count += dataItem.count;
});
});
const dateArray = Array.from(dateMap.values());
output[output.length - 1].data = dateArray;
const output = Object.values(result);
console.log(output);