0

I'm trying to get some math on an array of objects. Using the map for getting the value inside of the object and then reduce for made the calcules. For some reason reduce not return the correct value.

This is an example:

var test = [{
  id: 1,
  value: 2
}];
var newe = test.map((x) => x.value).reduce(function(total, sum) {
  console.log([total, sum]);
  return total + (sum * 2);
});

It's supposed to return 4, however, it returns 2.

Do you have an idea what is wrong? I share the code on jsfiddle https://jsfiddle.net/dleo7/ckgnrubh/10/

4
  • 1
    You forgot to give the reduce an initial value, so it doesn't iterate at all and only resolves to the value of the one value. Commented Jul 17, 2018 at 0:41
  • jsfiddle.net/ckgnrubh/11 Commented Jul 17, 2018 at 0:42
  • Always pass an initial value to reduce. Commented Jul 17, 2018 at 0:42
  • For those coming from google, note the first edge case here: "If the array only has one element (regardless of position) and no initialValue is provided, or if initialValue is provided but the array is empty, the solo value will be returned without calling callbackFn." Commented Sep 16, 2024 at 19:43

2 Answers 2

1

Doc from MDN

If initialValue isn't provided, reduce() will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0.

So, basically, your approach is skipping the first index 0 and the first value is returned 2. To solve this, you need to pass the initialValue, in this case, 0.

var test = [{
  id: 1,
  value: 2
}];
var newe = test.map((x) => x.value).reduce(function(total, sum) {
  return total + (sum * 2);
}, 0);
// ^
// |
// +---- InitialValue

console.log(newe);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

0

you should pass initial value to reduce function,

var test = [{
  id: 1,
  value: 2
}];
var newe = test.map((x) => x.value).reduce(function(total, sum) {
  console.log([total, sum]);
  return total + (sum * 2);
}, 0);

document.getElementById('output').innerHTML = newe;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.