添加数据集中所有对象的所有值

时间:2017-10-06 13:19:50

标签: javascript arrays dataset

所以我有一个有电影评级的数据集,每部电影都有多个评级。 我设法获得所有数据,但我想添加所有值。

例如:

title: avatar, rating: 2.5 title: avatar, rating: 3 title: avatar, rating 5

rating = 10.5

avrRating = 10.5 / ratings.lenght = 3.5

到目前为止我的代码:

(它选择一个随机电影,然后它将movieId与另一个数据集中的movieId匹配。然后我将范围从0-5转换为0-100以使其与data2中的宽度匹配.level [i] .rating显示了多个值,但我想要avarage值, 参见上面的示例

function willekeurigObject() {

  var blokje = document.querySelector("#data1");
  var blokje = document.querySelector("#data2");
  var blokje = document.querySelector("#data3");

  var willekeurigAdres = Math.floor(Math.random() * films.length);
  var willekeurigefilm = films[willekeurigAdres];

  for (var i = 0; i < rating.length; i++){
    if (rating[i].movieId == willekeurigefilm.movieId){
      var ratings = rating[i].rating;
    }
  }

  var width = (ratings / 0.05) + "%";


  data1.innerHTML = willekeurigefilm.title;
  data2.innerHTML = "<div class='stars'><img src='img/starsinv.png' class='img'></img><div class='yellow' style='width: " + width + "'></div></div>";
  data3.innerHTML = "";

}

setInterval(willekeurigObject, 3000);

1 个答案:

答案 0 :(得分:0)

您可以使用Array.prototype.reduce来添加数组中的所有值。

https://jsfiddle.net/khzcwnso/

var movies = [{title: 'avatar', rating: 2.5}, {title: 'avatar2', rating: 3}, {title: 'avatar3', rating: 5}];

var total = movies.reduce(function(sum, movie){
    return sum + movie.rating;
}, 0);

var average = total / movies.length;