Reputation: 851
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);
Upvotes: 0
Views: 52
Reputation: 1028
Just chain the reduce on to the map like:
const myArr = [3, 7, 8, "5", "9", 6, "2"];
function sumMix(x) {
return x.map((str) => {
return parseInt(str);
}).reduce((acc, cur) => {
return acc + cur;
});
}
sumMix(myArr);
Without chaining the reduce, like thers said, you are just returning the array result from the map, which correctly parses as integers but doesnt proceed on to reduce them
Upvotes: 1
Reputation: 44275
particularly the newer arrow function styles that don't require a return statement
It still returns something, the 'normal' braces can be omitted so the function directly returns the expression
Read more about arrow functions here
The map()
and reduce()
can be combined if we do an parseInt
on the cur
.
Remember to give 0
as initial value to reduce()
so we can simply add the parseInt(cur)
const myArr = [3, 7, 8, "5", "9", 6, "2"];
const sumMix = x => x.reduce((acc, cur) => acc + parseInt(cur), 0)
const res = sumMix(myArr);
console.log(res); // 40
Upvotes: 0