1 回答
TA贡献1906条经验 获得超3个赞
这是我的做法:
首先计算
age
从dob
每个人。然后使用reduce()来转换数据。如果一组中存在满足给定的标准,那么,我们当前成员添加到组,重新计算
sum
,oldest
和其它性质。如果没有,我们用当前成员创建一个新组。
const input = [ { name: 'Hendrick', dob: '1853-07-18T00:00:00.000Z', regNo: '041', }, { name: 'Albert', dob: '1910-03-14T00:00:00.000Z', regNo: '033', }, { name: 'Marie', dob: '1953-11-07T00:00:00.000Z', regNo: '024', }, { name: 'Neils', dob: '1853-10-07T00:00:00.000Z', regNo: '02', }, { name: 'Max', dob: '1853-04-23T00:00:00.000Z', regNo: '014', }, { name: 'Erwin', dob: '1854-08-12T00:00:00.000Z', regNo: '09', }, { name: 'Auguste', dob: '1854-01-28T00:00:00.000Z', regNo: '08', }, { name: 'Karl', dob: '1852-12-05T00:00:00.000Z', regNo: '120', }, { name: 'Louis', dob: '1852-08-15T00:00:00.000Z', regNo: '022', }, { name: 'Arthur', dob: '1892-09-10T00:00:00.000Z', regNo: '321', }, { name: 'Paul', dob: '1902-08-08T00:00:00.000Z', regNo: '055', }, { name: 'William', dob: '1890-03-31T00:00:00.000Z', regNo: '013', }, { name: 'Owen', dob: '1853-04-26T00:00:00.000Z', regNo: '052', }, { name: 'Martin', dob: '1854-02-15T00:00:00.000Z', regNo: '063', }, { name: 'Guye', dob: '1854-10-15T00:00:00.000Z', regNo: '084', }, { name: 'Charles', dob: '1954-02-14T00:00:00.000Z', regNo: '091', }, ];
// Compute age from DOB.
const data = input.map(item => {
let age = new Date().getFullYear() - new Date(item.dob).getFullYear();
return {...item, age};
});
var result = data.reduce((acc, curr) => {
let group = Object.values(acc).find(group => group.members && group.members.length < 3
&& group.members.every(member => Math.abs(member.age - curr.age) < 5));
if (group) {
group.members.push(curr);
group.regNos.push(curr.regNo);
group.oldest = Math.max(...group.members.map(member => member.age));
group.sum = group.sum + curr.age;
} else {
acc.noOfGroups = acc.noOfGroups + 1 || 1;
let groupName = "group" + acc.noOfGroups;
acc[groupName] = {
"members": [curr],
"oldest": curr.age,
"sum": curr.age,
"regNos": [curr.regNo],
};
}
return acc;
}, {});
console.log(result);
添加回答
举报