Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

This is an example of the data I have:

$scope.allmovies[
{title:"Harry Potter", time:130},
{title:"Star Wars", time:155},
{title:"Lord of the Rings", time:250},
{title:"Goonies", time:125},
{title:"Fast and Furious", time:140}
];

var mostpopular=[
$scope.allmovies[0],
$scope.allmovies[2]
];

var recentlyadded=[
$scope.allmovies[1],
$scope.allmovies[3],
$scope.allmovies[4]
];

$scope.playlists={

mostpoplularmoves:{
title:"Most Popular Movies",
price:"$5.99",
Number:mostpopular.length,
TotalTime: LOOP THROUGH VAR MOSTPOPULAR AND ADD TIME TO GET A TOTAL TIME OF ALL MOVIES
},

recentlyaddedmovies:{
title:"Recently Added Movies",
price:"$2.99",
Number:recentlyadded.length,
TotalTime:LOOP THROUGH VAR RECENTLYADDED AND ADD TIME TO GET A TOTAL TIME OF ALL MOVIES
}

};

So I just need to loop through the above arrays and add up all the time to get a total time of the each playlist (mostpopular[0].time+=totalTime then mostpopular[1].time+=totalTime etc.... or something like that). Is this possible and if so, what would be the syntax? Thanks in advance

share|improve this question
    
Sorry about that :) – MehdiN yesterday

You can use a reduce function for that

mostpopular.reduce(function(totalTime, movie) {
  return totalTime + movie.time;
}, 0);

reduce functions use an accumulator(totalTime) and then the second argument in the current value in the array. The 0 at the bottom represents what we should use as the initial totalTime argument.then after altering totalTime in the reduce return that will be the totalTime argument for the next item in the array.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.