简体   繁体   中英

How to return an array of the total - reduce function - Javascript

I have this array of movies, I'm trying to use the reduce function and the expected output should be: 420(the total duration of the 3 objects), the output I'm getting right now is like a concatenation of the 3 strings, why is that?

 let movies = [ { 'name': 'Jumanji', 'duration': 120 }, { 'name': 'Harry Potter', 'duration': 60 }, { 'name': 'Toy Story', 'duration': 240 } ]; let newAr = movies.reduce((previousValue, currentValue) => [ previousValue + currentValue.duration ], []); console.log('newAr', newAr)

The previousValue will be the accumulator, the value returned by the prior iteration of the callback - or, the initial value - so it'll be an array. Doing someArray + someOtherValue will coerce the array into a string (in other words, doing .join(',') ) and concatenate it with the expression on the right.

I'd map the movies to their durations instead, then add them up:

const totalDuration = movies
  .map(m => m.duration)
  .reduce((a, b) => a + b, 0);

Or do it in one step, though it might be a bit harder to parse at a glance if you're unfamiliar with reduce .

const totalDuration = movies
  .reduce((a, movie) => a + movie.duration, 0);

 const movies = [ { 'name': 'Jumanji', 'duration': 120 }, { 'name': 'Harry Potter', 'duration': 60 }, { 'name': 'Toy Story', 'duration': 240 } ]; console.log(movies.reduce((previousValue, currentValue) => previousValue + currentValue.duration, 0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM