DEV Community

Discussion on: array.map(): A better way 🧐 ?

Collapse
 
marceliwac profile image
Marceli-Wac

I'm not sure I see the value here, provided it's just syntactical difference (it's not, see the other comments). If it were just a matter of syntactical sugar, this whole post could have been addressed by bringing the Array.forEach() to Author's attention, which in the simpler terms, is an "Array.map()"-like syntax for for-loop.

i.e.

newArray = [];

oldArray.forEach((element, index, thisArray) => {
   // Access the index of the current element
   console.log("Handling element at", index, "index of old array");

   // Work on the current element of the array
   newArray.push(transformElement(element));

   // Access the elements of the current array at specific index:
   thisArray[index] = {...element, transformed: true}
}
Enter fullscreen mode Exit fullscreen mode

The main benefit of taking thisArray as the last argument to lambda is the fact that you can encapsulate the behaviour in a named function (here a lambda is provided). Rest is pretty obvious.

Collapse
 
sereneinserenade profile image
Jeet Mandaliya

In the task I mentioned above for reversing strings and putting them in a new array, I agree that forEach is a good approach.

I personally would still prefer map() over forEach() because

  1. we don't have to push element to newArray manually
  2. since map() returns an array. we can do further processing on array like filtering and sorting right there after running map() without ever need to manipulate newArray.

For example.

const oldArr: string[] = ['anhsirK', 'nosaJ', 'nolE', 'drawdE']
const newArray: string[] = oldArr.map((element) => element.split("").reverse().join("")).sort((a, b) => a > b ? 1 : -1)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
marceliwac profile image
Marceli-Wac

totally agree!