/* You need to write a function to calculate the sum of all numeric values in an array. Valid numeric values also include strings that start with digits. In this case, the numeric value should be the initial sequence of digits. The array can contain any data types and may be nested. **You cannot use built-in methods like .flat, .flatMap** */ function sum(arr) { // ... } console.log(sum([1, 'x', '2x', ['3', ['x2', '5']]]));
sobes.tech AI
Answer from AI
javascript function sum(arr) { let total = 0;
function helper(a) { for (const item of a) { if (typeof item === 'number') { total += item; } else if (typeof item === 'string') { const match = item.match(/^\d+/); if (match) { total += Number(match[0]); } } else if (Array.isArray(item)) { helper(item); } // Other types are ignored } }
helper(arr); return total; }
console.log(sum([1, 'x', '2x', ['3', ['x2', '5']]])); // 11
// The function recursively traverses the array, checking each element:
// - If it's a number, adds it to the sum.
// - If it's a string, attempts to extract the leading digits and add them.
// - If it's an array, calls itself recursively.
// - Other types are ignored.
//
// This way, it sums all numeric values and strings starting with digits without using .flat or .flatMap.