The prevValue becomes undefined, but when I remove the conditional lines (170) above undefined is gone.
But when I add the prevValue as condition in the line 173, it won't perform the line below anymore.
What I wanted is when a condition is meet, then I can push an item inside prevValue.
I have the whole example that we can examine here in codesandbox https://codesandbox.io/s/goofy-feather-t79kb6?file=/src/index.js
Sorry, I spent hours on this simple one yet time consuming for me. Your help is highly appreciated. Thank you.
The returned value of the callback function becomes the new accumulated value, with every iteration.
So, if we are not updating it, we have to return the old value itself.
arr.reduce((acc,item)=>{
if(condition) return acc.concat(item);
//else
return acc; //-->should not miss this.
},[])
I think this eslint rule https://eslint.org/docs/rules/array-callback-return will help catch this type of issues early.