Array#reduce
is a method specific to arrays that requires a function to be passed as an argument. You've defined a function, but have not invoked it.
To fix this issue, you can try the following:
let arr = [1, [2, 3], 4];
let newarr = [];
((array) => {
for(let i=0; i < array.length; i++) {
const el = array[i];
const topush = Array.isArray(el) ? el.reduce((total, curr) => total + curr, 0) : el;
newarr.push(topush)
}
})( arr );
console.log( newarr );
Alternatively, you can achieve the same result using both Array#map
and Array#reduce
. The key in both cases is to identify when to apply the reduce
method on the array elements:
const arr = [1, [2, 3], 4, [4, 5, 7]];
const newarr = arr.map(el =>
Array.isArray(el) ? el.reduce((sum,cur) => sum + cur, 0) : el
);
console.log( newarr );