I’m working on a challenge as part of a take-home interview challenge and I’ve run into a really strange error with the reduce method. I’m rendering a list of products and I have to label the best-seller based on a “units sold” property. I’ve tried using the reduce method as follows:
let bestNum = this.props.wines.reduce((a, b) => {
return Math.max(a.unitsSold, b.unitsSold);
});
This should work as I’ve tested it using a mock array in a repl. However when using this with React I get the error: “React.createElement: type is invalid”. I realized that it’s giving me this error because of the missing argument after the callback but from what I’ve read in the documentation, this argument is optional. So why won’t it play nice with React?
Yeah I’m using it in the render method. I’m only getting this error when omitting the accumulator argument. If I were to put “0” as the accumulator, the error disappears and I get a result, just not a result I want of course.
I did find a workaround in the meanwhile, however by doing this:
Written like this, I think the initial accumulator is optional - previously, you were trying to access a property on an undeclared var (I think) which is probably what was causing the issue.
…in addition to @r1chard5mith answer:
js .reduce is actually two functions glued together - fold and reduce.
reduce reduces multiple entities into one of same type, think about array of numbers into number, or array of strings into one string. To do that, you don’t actually need initial accumulator value, since first element can be used as one.* **
fold folds one entity into another - array of numbers into array of strings, one number or even object. To do that, you need to provide some initial value, because function can’t figure it for itself.