I'm new to javascript and I'm having difficulty keeping up with the various ways of writing functions, particularly the newer arrow function styles that don't require a return statement.
I spent a while trying to write a function that takes a string containing both numbers and number strings, converts all into numbers and then gets the sum / total.
From what I can gather, I was on the right path by trying to use the map()
method to return a new array, followed by parseInt
to change the strings to numbers, and finally reduce()
to get the sum.
When I tried this, the reduce method would not work, and I would be left with the array of numbers.
Someone else wrote a solution that works that uses the same steps as mine, but I am struggling to work out how this would work when written in the longer format that I have learned (I haven't extensively studied shorter form ES6 arrow functions yet).
Any advice on how I could change my function so that it works like the shorter one would be greatly appreciated.
My function:
const myArr = [3, 7, 8, "5", "9", 6, "2"];
function sumMix(x) {
return x.map((str) => {
return parseInt(str);
});
str.reduce((acc, cur) => {
return acc + cur;
});
}
sumMix(myArr);
The working solution I found
const myArr = [3, 7, 8, "5", "9", 6, "2"];
function sumMix(x){
return x.map( str => parseInt(str)).reduce( (acc, cur) => acc + cur );
}
sumMix(myArr);