I wanted to point out that you could also have used map in a different way and still have the expected result.
constroot=document.getElementById("root");if(!root){thrownewError("Root not found");}constfruits=["banana","apple","pear"];constindexed=fruits.map((fruit,index)=>{return`#${index+1}: ${fruit}`;});consthtml=indexed.join("<br>");root.innerHTML=html;
Although I agree with you, I would change the title from Stop using Array.prototype.map everywhere to Start learning when to use Array.prototype.map.
A do/don't kind of article would have been great for beginners to quickly catch the idea, and maybe extend the article to some of the most popular array methods as well.
Well, if you are going with Array.prototype.reduce, you better be not using any side-effects.
constroot=document.getElementById("root");if(!root){thrownewError("Root not found");}constfruits=["banana","apple","pear"];constinnerHTML=fruits.reduce((html,fruit,index)=>{return`${html}#${index+1}: ${fruit}<br>`;},"");root.innerHTML=innerHTML;
Hi @suprabhasupi and thanks for your article.
I wanted to point out that you could also have used map in a different way and still have the expected result.
Although I agree with you, I would change the title from
Stop using Array.prototype.map everywhere
toStart learning when to use Array.prototype.map
.A do/don't kind of article would have been great for beginners to quickly catch the idea, and maybe extend the article to some of the most popular array methods as well.
I should start making comprehensive guides, so I can gain popularity, since my YT career's dead.
It's better to use Reduce for this task.
const fruits = ["banana", "apple", "pear"];
fruits.reduce((initalArr, value, currentIndex) => {
initalArr.push(
${currentIndex} --- ${value}
);return initalArr;
}, []);
Well, if you are going with
Array.prototype.reduce
, you better be not using any side-effects.It's a common mistake that devs do sometimes, and the above example suits here, Thanks for sharing this ☺️