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

Cannot generate required string with reduce in JS

I have this error and can not solve this. I tried looking for asked questions and none answers my problem.I tried working with the code, it looks simple but yet confusing as I’m just learning this.
I want output as Nepal, China and the United States

I have this code:

import { countries } from "./data.js";
console.log(countries.reduce((x='',country)=>{
   if(!x.includes('and')){ 
/*array does not contain and & we need    
terminate if statement for the last value of x.*/
    x += (country +", ")
   }else{
    x +=(' and the ' + country)
   }
   return x;
}))

Countries is an array
[‘Nepal’,’China’,’United States’]

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

and the output that I am getting is: `NepalChina, United States, `.
Thanks for looking into this.

>Solution :

let countries = ['Nepal','China','United States'];
console.log(countries.reduce((x, country, index, countries) => {
  if(index === countries.length - 1)
    return x += ', and ' + country;
  else
    return x += ', ' + country;
}));

We need to remove the check for and since that isn’t present in the initial array. We also need to know when we are on the last iteration here which I’ve done above by checking if(index === countries.length - 1)

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