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’]
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)