gpt4 book ai didi

javascript - 使用 JavaScript 求和函数

转载 作者:行者123 更新时间:2023-12-01 03:44:31 25 4
gpt4 key购买 nike

我正在尝试计算每月的门票数量。我拥有的数组:

[['tickets', 'month','year'], [1, "june",2016],[3, "june",2015],[1, "december",2015]]

我想要的结果:

[['year', 'june','december'], [2016,1,0],[2015,3,1]]

但我不知道如何用 JavaScript 来做到这一点。有什么帮助吗?谢谢,

最佳答案

一种可能的方法:我将日期分组到一个对象中,创建一个包含条目的唯一月份数组,然后将其处理为您想要的数组。

var inArray = [['tickets', 'month','year'], [1, "june",2016],[3, "june",2015],[1, "december",2015]]
var validMonths = {}

function dateReducer (acc, curr) {
var year = curr[2]
var month = curr[1]
var num = curr[0]
if (year === "year"){return acc}
validMonths[month] = 0 // build unique array of valid months

if (!acc[year]) {
acc[year] = {}
acc[year][month] = num
} else {
if (!acc[year][month]) {
acc[year][month] = num
} else {
acc[year][month] += num
}
}
return acc
}

var obj = inArray.reduce(dateReducer, {})
// This may be fine, depending on your needs
validMonths = Object.keys(validMonths)
var outArray = ["year"].concat(validMonths)

for (var year in obj) {
if (obj.hasOwnProperty(year)){
var subArray = [year]
validMonths.forEach(v => {
subArray.push(obj[year][v] || 0)
})
outArray.push(subArray)
}
}

console.log(outArray)

关于javascript - 使用 JavaScript 求和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43639283/

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