gpt4 book ai didi

javascript - 如何统计每种类型的实例数?

转载 作者:行者123 更新时间:2023-12-04 02:25:17 25 4
gpt4 key购买 nike

const data = ['soccer', 'soccer', 'basketball', 'basketball', 'badminton', 'swimming', 'soccer', 'squash', 'badminton', 'swimming', 'soccer', 'squash', 'soccer', 'basketball', 'fencing'];

const sports = data.reduce(function(obj, item) {
if (!obj[item]) //to create an object if it doesn't exist
obj[item] = 0;
else
obj[item]++; //to increment the object count if it exist
return obj;
}, {});

console.log(sports);

我收到的输出:

Object { soccer: 0, basketball: 0, badminton: 0, swimming: 0, squash: 0, fencing: 0 }

我想要的输出:

Object { soccer: 5, basketball: 3, badminton: 2, swimming: 2, squash: 2, fencing: 1 }

出了什么问题?

最佳答案

在 JavaScript 中,零 evaluates to false .
所以 !obj[item]trueobj[item] == 0 并且什么都不会递增。

const obj = {
'soccer': 0
};

// true
console.log(!obj['basketball']);

// also true!
console.log(!obj['soccer']);

一个解决方案是将新属性初始化为 1 而不是 0。无论如何,任何值都不能为零,因为每个属性在数据集中至少存在一次,这可以避免将零与未定义混淆。

const data = ['soccer', 'soccer', 'basketball', 'basketball', 'badminton', 'swimming', 'soccer', 'squash', 'badminton', 'swimming', 'soccer', 'squash', 'soccer', 'basketball', 'fencing'];

const sports = data.reduce(function(obj, item) {
if (!obj[item])
obj[item] = 1; // initialize property to 1 if it is falsy
else
obj[item]++; // otherwise increment the value
return obj;
}, {});

console.log(sports);

但在我看来,else 是不必要的,Andy's method有点简单。

只是为了好玩,这是使用 ternary operator 的另一种方法:

const data = ['soccer', 'soccer', 'basketball', 'basketball', 'badminton', 'swimming', 'soccer', 'squash', 'badminton', 'swimming', 'soccer', 'squash', 'soccer', 'basketball', 'fencing'];

const sports = data.reduce(function(obj, item) {
obj[item] = obj[item] ? obj[item] + 1 : 1;
return obj;
}, {});

console.log(sports);

another method来自 snak :

const data = ['soccer', 'soccer', 'basketball', 'basketball', 'badminton', 'swimming', 'soccer', 'squash', 'badminton', 'swimming', 'soccer', 'squash', 'soccer', 'basketball', 'fencing'];

const sports = data.reduce(function(obj, item) {
obj[item] = (obj[item] || 0) + 1;
return obj;
}, {});

console.log(sports);

供引用,另见:
How to increment an object property value if it exists, else set the initial value?
short javascript code for: initialize to zero or increment
Count the occurrence of each word in a phrase using javascript

关于javascript - 如何统计每种类型的实例数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68242492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com