Here are a couple of pointers to consider:
- When using the reduce function, remember to adjust the second parameter as it represents the initial value. The first parameter in the reduce callback (acc) is your accumulated value up to that specific iteration.
- Ensure that you return your accumulated value in each iteration. This becomes your final answer in the last iteration. If you fail to return anything, it results in 'undefined' being returned.
const multiplyOddByTwo = (arr) => {
return arr.reduce((acc, curr) => {
if (curr % 2 === 0) {
acc.push(curr);
} else {
acc.push(curr * 2)
}
return acc;
}, [])
}
console.log(multiplyOddByTwo([1, 2, 3])); // [2,2,6]
This function multiplies odd-indexed elements by 2.
Note: The result isn't an undefined error, it's simply the return of undefined
. Any function that doesn't explicitly return something will default to returning undefined
.