Summing Array Values in JavaScript
This challenge focuses on a fundamental programming task: calculating the sum of all numerical values within an array. This is a common operation in data processing, statistics, and many other areas of software development, and mastering it is a crucial first step in understanding array manipulation.
Problem Description
You are tasked with writing a JavaScript function called sumArray that takes a single argument: an array of numbers. The function should iterate through the array and return the sum of all the numbers present within it. The function should handle various scenarios, including empty arrays and arrays containing non-numeric values (which should be treated as 0).
Key Requirements:
- The function must be named
sumArray. - It must accept a single argument: an array of numbers.
- It must return a single number representing the sum of all elements in the array.
- Non-numeric values within the array should be treated as 0.
- The function should handle empty arrays gracefully, returning 0.
Expected Behavior:
The function should accurately calculate the sum of all numbers in the input array, ignoring any non-numeric values. It should return 0 if the array is empty.
Edge Cases to Consider:
- Empty array:
[] - Array with only numbers:
[1, 2, 3] - Array with mixed numbers and non-numeric values:
[1, "hello", 2, true, 3, null, 5](treat "hello", true, and null as 0) - Array with negative numbers:
[-1, 2, -3] - Array with floating-point numbers:
[1.5, 2.5, 3.5]
Examples
Example 1:
Input: [1, 2, 3, 4, 5]
Output: 15
Explanation: The function sums all the numbers in the array: 1 + 2 + 3 + 4 + 5 = 15
Example 2:
Input: [1, "hello", 2, true, 3, null, 5]
Output: 11
Explanation: The function sums the numeric values, treating non-numeric values as 0: 1 + 0 + 2 + 0 + 3 + 0 + 5 = 11
Example 3:
Input: []
Output: 0
Explanation: The function returns 0 for an empty array.
Constraints
- The input array will contain numbers and potentially other data types (strings, booleans, null, undefined).
- The array can contain positive, negative, and floating-point numbers.
- The array can be empty.
- The function should execute efficiently for arrays of up to 10,000 elements.
Notes
Consider using a loop (e.g., for loop or forEach) to iterate through the array. You'll need to check the type of each element before adding it to the sum. The typeof operator or Number.isNaN() can be helpful for type checking. Remember to initialize the sum to 0 before starting the iteration.