const array = [1, 2, 3, {}, NaN, [2, 4, 5, []]]
const sum = data =>
Array.isArray(data)
? data.reduce((acc, n) => acc + sum(n), 0)
: (+data || 0);
function sum(data) {
let result = 0;
for (const stack = [ data ]; stack.length;) {
const n = stack.pop();
if (n instanceof Array) {
stack.push(...n);
} else {
result += +n || 0;
}
}
return result;
}
true
, '0xBB'
, { valueOf: () => 666 }
и т.д.let print = s => console.log(s);
let arr = [1,'3', 2, 3, {}, NaN, [2, 4, 5, []]];
arr = arr.flat(Infinity);
let sum = 0;
for(let el of arr) {
if(Number.isFinite(el)) sum += el;
}
print(sum);
let print = s => console.log(s);
let arr = [1, '3', 2, 3, {}, NaN, [2, 4, 5, [] ]];
let sum = arr.flat(Infinity).filter(el => Number.isFinite(el)).reduce((acc,el) => acc + el, 0);
print(sum);