DEV Community

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

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!