简体   繁体   中英

How do I assign my .reduce function output to a variable?

Given an object and a key, getElementsThatEqual10AtProperty returns an array containing all the elements of the array located at the given key that are equal to ten.

I want to assign what my .reduce method outputs to a variable then use that variable inside my if statement. My code evaluates to NaN .

function getElementsThatEqual10AtProperty(obj, key) {
  var arrayTotal = 0;
  obj[key].reduce(function(a,b){
    arrayTotal = a + b;
   });
  if(arrayTotal === 10) {
    return obj[key];
  }
};

You're approaching reduce incorrectly. You're almost using it like Array#forEach . Remember that callbacks are functions. They expect to return an actual value.

When you read the docs, you'll see that reduce also needs an accumulator , that is an argument after the callback.

const sum = obj[key].reduce(function(a,b){
  return a + b
}, 0)

Or if you want the newer and prettier version:

const sum = obj[key].reduce((a,b) => a + b, 0)

When you have a one liner, return is implicit, which means it's implied, as opposed to explicit.

The accumulator is what your value starts at while it totals up the values.

Array.reduce(callback, accumulator)

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