CHALLENGE:
Sum Mixed Array
Given an array of integers as strings and numbers, return the sum of the array values as if all were numbers.
Return your answer as a number.
PREP
Parameters
- An array of integers as strings and numbers. ex: [9, “9”]
- Positive, whole numbers only
Returns
- The sum (as an integer) of the array values, as if all were integers.
Examples / Tests
- console.log(sumMix([9, 3, ‘7’, ‘3’]), 22);
- console.log(sumMix([‘5’, ‘0’, 9, 3, 2, 1, ‘9’, 6, 7]), 42);
- console.log(sumMix([‘3’, 6, 6, 0, ‘5’, 8, 5, ‘6’, 2,’0′]), 41);
Pseudocode
- Using arr.reduce((a, c) => a + c) would work if all elements in the array were integers to begin with. But they’re not, some are strings.
- In order to convert the sum to a number, we can do Number(c)
- .reduce(a, c) takes in accumulator, current value
- Number(n) creates a new Number value, we want to change the current value to a Number
Solution
function sumMix(arr) {
return arr.reduce((a, c) => a + Number(c), 0)
}
Further Exploration
- Map MDN
- Reduce MDN
- Number MDN
- What does Number return if the string can’t be converted to a number? When used as a function, Number(value) converts a string or other value to the Number type. If the value can’t be converted, it returns NaN.
- Why is the 0 important? because it catches a possible empty array and makes sure the answer is zero rather than undefined.
- Reduce syntax – can you write it by heart?