gpt4 book ai didi

javascript - 计算数组中不同元素的数量

转载 作者:行者123 更新时间:2023-11-28 20:29:19 27 4
gpt4 key购买 nike

我有来自服务器到数据表的数据。我已成功填充表格,但在页脚回调中我想进行一些统计。

假设我有这样的数据:

var data = [{
date: '2013-05-12',
holiday: "One type of holiday",
dayType: "Weekend"
}, {
date: '2013-05-13',
holiday: "Another type",
dayType: "Weekend"
}, {
date: '2013-05-14',
holiday: "Another type",
dayType: "Work"
}, {
date: '2013-05-15',
holiday: "",
dayType: "Work"
}];

我想计算不同假期的天数。

这是我想要得到的结果:

var summary= [
{
"One type of holiday": {
"work": 0,
"weekend": 1
}
},
{
"Another type": {
"work": 1,
"weekend": 1
}
}];

I've created a very simple code to simply aggregate holidays :

for (var i = 0; i < data.length; i++) {
//console.log(data[i].holiday);
/*other stuff here*/
if (data[i].holiday.length > 0)
summary[data[i].holiday] = summary[data[i].holiday] + 1 || 1;
}

但这给了我无效的结果,因为在我的数据数组中假期包含空格。

我需要一种方法来解决这个问题并根据 dayType 分割假期。

<小时/>

我的解决方案: My version of answer :

var summary = {}, d, tmp, type;
for (var i = 0; i < data.length; i++) {
var d = data[i];
if (d.holiday.length > 0) {
type = d.dayType == 'Weekend' || d.dayType == 'Free' ? 'Weekend' : 'Work';
tmp = summary[d.holiday];
if (!tmp) {
tmp = {
Weekend: 0,
Work: 0
};
summary[d.holiday] = tmp;
}
summary[d.holiday][type] += 1;
}
}

因为这是 @Arun 答案的修改版本,所以我不会将其作为独立答案发布。
我发现我的版本更容易理解,希望有人觉得它有用。

最佳答案

尝试

var summary = [], summaryMap = {}, d, map, m;
for (var i = 0; i < data.length; i++) {
var d = data[i];
map = summaryMap[d.holiday];
if(!map){
map = {
Work: 0,
Weekend: 0
};
m = {};
m[d.holiday] = map;
summary.push(m);
summaryMap[d.holiday] = map;
}
map[d.dayType] += 1;
}
console.log(summary);
console.log(JSON.stringify(summary));

演示:Fiddle

关于javascript - 计算数组中不同元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16730526/

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