Middle
Write a function that takes an array of numbers and strings and returns the sum of all elements, converting strings to numbers. How to handle strings containing non-numeric characters?
sobes.tech AI
Answer from AI
To solve the problem, you can iterate over the array, converting strings to numbers using the Number or parseFloat function. If the string contains non-numeric characters, the conversion will result in NaN. To handle such cases, you need to check the conversion result and ignore or process elements that could not be converted to a number.
Example function in JavaScript:
function sumArray(arr) {
return arr.reduce((sum, item) => {
let num = typeof item === 'string' ? Number(item) : item;
if (isNaN(num)) {
// Ignore elements that cannot be converted to a number
return sum;
}
return sum + num;
}, 0);
}
// Example usage:
const data = [10, '20', '30a', '40', 5];
console.log(sumArray(data)); // Outputs 75 (ignores '30a')
Thus, strings with non-numeric characters do not affect the sum, as they are skipped.