我有以下数组,它们已经排序:
day = [5,5,5,6,6, 6, 6,7,7,7, 8, 8,8];
time = [0,0,0,0,0,1.03,0.28,0,0,0,0.63,5.58,1];
class = [ , , , , , b, b, , , , c, b,c];
我想消除day数组中的重复值,并在time数组中添加相应的值,但仅对于相应的类,如果类为空,则为零,这将是这样的:
day_fix = [5, 6,7, 8];
class_b = [0,1.31,0,5.58];
class_c = [0, 0,0,1.63];
谢谢。
答案 0 :(得分:0)
我认为以下内容可能会对您有所帮助:
const day = [5,5,5,6,6, 6, 6,7,7,7, 8, 8, 8]
const time = [0,0,0,0,0,1.03,0.28,0,0,0,0.63,5.58, 1]
const clazz = [ , , , , , 'b', 'b', , , , 'c', 'b','c']
const resultDays = {}
day.forEach((d, i) => {
resultDays[d] = resultDays[d] || {}
if (clazz[i]) {
resultDays[d][clazz[i]] = (resultDays[d][clazz[i]] || 0) + time[i]
}
})
console.log(resultDays)
输出是一个对象,只是您提供的结果的另一种表示形式。这样一来,它将变得更加容易,因为它不再需要为每个类创建单独的数组。