识别和添加数组中的值


class Member {
constructor (membershipType, pointsEarned) {
this.membershipType = membershipType;
this.pointEarned = pointsEarned;
}
}
var John = new Member ('Gold', 1400);
var Luke = new Member ('Ruby', 250);
var Sam = new Member ('Gold', 3350);
var Kelly = new Member ('Diamond', 40200);
Output:
ruby: 250
gold: 4750
platinum: 0
diamond: 40200

我想要实现的是添加"pointEarned"关联到相同"membershiptype"的值。分别加在一起

例如,如果有2个黄金"membershipType",我想加上1400 "3350年在一起。我能做到吗?

我使用for循环遍历"membershiptype"。然而,我仍然无法理解它。这是我尝试过的代码,但它没有意义。

for (var i = 0; i < memberGroup.length; i++) {
if ("Ruby" == memberGroup[i]["membershipType"]) {
for (let x in memberGroup[i]) {
}
}
}
console.log ("ttruby: " + (subMemTypeCount["Ruby"] ?? 0));
console.log ("ttgold: " + (subMemTypeCount["Gold"] ?? 0));
console.log ("ttplatinum: " + (subMemTypeCount["Platinum"] ?? 0));
console.log ("ttdiamond: " + (subMemTypeCount["Diamond"] ?? 0));

我将尝试在不使用您的原始代码的情况下解释这一点,只是为了尽量保持最小化。

所以让我们忘记有一个类,因为它现在是代码中的额外噪音。我们也可以简单地定义一个对象字面量:

var John = { membershipType: 'Gold', pointsEarned: 1400 };

如果没有看到memberGroup,我们可以假设它是某种数组,如:

const memberGroup = [
John,
Luke,
Sam,
Kelly,
];

看看你的代码,我们可以看到你想要得到每种类型的和。最好把这些类型存储在某个地方,这样我们就知道要找的是什么了:

const types = [
'Gold',
'Ruby',
'Platinum',
'Diamond'
];

现在我们需要知道如何得到给定类型的和:

const sumForType = (type, members) => members
.reduce(
(currentSum, member) => {
if (member.membershipType === type) {
return currentSum + member.pointsEarned;
}
return currentSum;
}
);

Reduce是一种很好的方法来获取多个东西,并将它们减少到单个值。

那么现在,我们可以得到每种类型的和:

const subMemTypeCount = types.reduce(
(sumsForTypes, type) => {
sumForTypes[type] = sumForType(type, memberGroup);
return sumsForTypes;
},
{},
);

所以,把它们放在一起,我们得到这样的东西:

var John = { membershipType: 'Gold', pointsEarned: 1400 };
var Luke = { membershipType: 'Ruby', pointsEarned: 250 };
var Sam = { membershipType: 'Gold', pointsEarned: 3350 };
var Kelly = { membershipType: 'Diamond', pointsEarned: 40200 };
const memberGroup = [
John,
Luke,
Sam,
Kelly,
];
const types = [
'Gold',
'Ruby',
'Platinum',
'Diamond'
];
const sumForType = (type, members) => members
.reduce(
(currentSum, member) => {
if (member.membershipType === type) {
return currentSum + member.pointsEarned;
}
return currentSum;
},
0,
);
const subMemTypeCount = types.reduce(
(sumsForTypes, type) => {
sumsForTypes[type] = sumForType(type, memberGroup);
return sumsForTypes;
},
{},
);
console.log(subMemTypeCount);

或者,如果是我,我会这样写😊:

const John = { membershipType: 'Gold', pointsEarned: 1400 };
const Luke = { membershipType: 'Ruby', pointsEarned: 250 };
const Sam = { membershipType: 'Gold', pointsEarned: 3350 };
const Kelly = { membershipType: 'Diamond', pointsEarned: 40200 };
const propEq = p => k => o => o[p] === k;
const prop = k => o => o[k];
const hasType = propEq('membershipType');
const getPoints = prop('pointsEarned');
const sum = (x, y) => x + y;
const sumForType = (...members) => type => members
.filter(hasType(type))
.map(getPoints)
.reduce(sum, 0);
const getSumForMembers = sumForType(John, Luke, Sam, Kelly);
const typeSums = ['Gold', 'Ruby', 'Diamond', 'Platinum'].reduce(
(p, c) => ({
...p,
[c]: getSumForMembers(c),
}),
{},
);
console.log(typeSums);

可以考虑有两个类——一个定义Member,另一个定义Member组。然后,您可以将一个新的成员对象数组传递给Members,并使用reduce对该数组对象计算总数。

class Members {

// Assign the array of members to `members`,
// and define some default types
constructor(members) {
this.members = members;
this.types = ['Gold', 'Ruby', 'Diamond', 'Platinum'];
}
// Use the default types to create an object of key/value
// pairs where each value is set to zero
initaliseTypes() {
return this.types.reduce((acc, c) => {
acc[c] = 0;
return acc;
}, {});
}
getTotals() {
// Use `reduce` to iterate over the `members` array
// and add up the values for each `type`
return this.members.reduce((acc, c) => {
// Destructure the type and value from
// the current object
const { type, value } = c;
// We pass in out intialised types object
// as the initial reduce object (accumulator).
// On each iteration we add the value to the 
// object where the key matches the type.
// Then return the accumulator for the next iteration
acc[type] += value;
return acc;
}, this.initaliseTypes())
}
}
class Member {
// Assign each key/value pair to `this`
constructor(member) {
for (const prop in member) {
this[prop] = member[prop];
}
}
}
const members = new Members([
new Member({ name: 'John', type: 'Gold', value: 1400 }),
new Member({ name: 'Luke', type: 'Ruby', value: 250 }),
new Member({ name: 'Sam', type: 'Gold', value: 3350 }),
new Member({ name: 'Kelly', type: 'Diamond', value: 40200 })
]);
console.log(members.getTotals());

额外documenation

  • 解构作业

  • 逻辑空赋值

相关内容

  • 没有找到相关文章