Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I write this function with longer syntax?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading