我试图在Javascript / jQuery中找到一种有效的方法来执行以下操作:
我得到了一个包含对象的数组,每个对象都包含一个日期和一个等级。许多条目具有相同的日期。我想创建另一个对象数组,每个对象包含日期(唯一)和该日所有收视率的平均值。
示例数据:
$(".DCA-FormField input:not(.sapMComboBoxInner), .sapMInputBaseInner, .sapMComboBox").css({fontSize:'20px'});
我的追求:
var array = [{
date: "07-08-2018"
rating: 3
},{
date: "07-08-2018"
rating: 5
},{
date: "08-08-2018"
rating: 2
},{
date: "08-08-2018"
rating: 1
},{
date: "09-08-2018"
rating: 3
},{
date: "09-08-2018"
rating: 5
}
]
我当前的代码(仅返回2个值而不是3个值)
var averageArray = [{
date: "07-08-2018",
rating: 4
},{
date: "08-08-2018",
rating: 1.5
},{
date: "09-08-2018",
rating: 4
}]
答案 0 :(得分:2)
对事物进行分组的最好方法是创建一个使用公用值作为属性键的对象。
然后将它们分组在该对象中后,将结果映射到新数组
var tmp ={};
data.forEach(function(item){
// if property for current date already exists we update existing otherwise start new one
var obj = tmp[item.date] = tmp[item.date] || {count:0, total: 0};
// increment count and total of all the ratings
obj.count ++;
obj.total += item.rating
});
var res = Object.entries(tmp).map(function(entry){
return { date: entry[0], ave: entry[1].total/entry[1].count}
})
console.log( res)
<script>
var data = [{
date: "07-08-2018",
rating: 3
},{
date: "07-08-2018",
rating: 5
},{
date: "08-08-2018",
rating: 2
},{
date: "08-08-2018",
rating: 1
},{
date: "09-08-2018",
rating: 3
},{
date: "09-08-2018",
rating: 5
}
]
</script>