DEV Community

Discussion on: Stop using Array.map() everywhere 🥵

Collapse
 
aminnairi profile image
Amin • Edited

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.

const root = document.getElementById("root");

if (!root) {
  throw new Error("Root not found");
}

const fruits = ["banana", "apple", "pear"];

const indexed = fruits.map((fruit, index) => {
  return `#${index + 1}: ${fruit}`;
});

const html = indexed.join("<br>");

root.innerHTML = html;
Enter fullscreen mode Exit fullscreen mode

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.

Collapse
 
baenencalin profile image
Calin Baenen

I should start making comprehensive guides, so I can gain popularity, since my YT career's dead.

Collapse
 
hellnar profile image
Stas Klymenko

It's better to use Reduce for this task.

Collapse
 
mehuljariwala profile image
Mehul Jariwala

const fruits = ["banana", "apple", "pear"];
fruits.reduce((initalArr, value, currentIndex) => {
initalArr.push(${currentIndex} --- ${value});
return initalArr;
}, []);

Thread Thread
 
aminnairi profile image
Amin

Well, if you are going with Array.prototype.reduce, you better be not using any side-effects.

const root = document.getElementById("root");

if (!root) {
  throw new Error("Root not found");
}

const fruits = ["banana", "apple", "pear"];

const innerHTML = fruits.reduce((html, fruit, index) => {
  return `${html}#${index + 1}: ${fruit}<br>`;
}, "");

root.innerHTML = innerHTML;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
suprabhasupi profile image
Suprabha

It's a common mistake that devs do sometimes, and the above example suits here, Thanks for sharing this ☺️

Some comments have been hidden by the post's author - find out more