DEV Community

Aaron Eiche
Aaron Eiche

Posted on

Useful JS functions you aren't using: Array.map

I learned Javascript the hard way: I stumbled into web development and kept on stumbling my way through the stack until I could program competently. Some days I'm still stumbling my way through.

Because of the way I learned, picking up what I needed only when I needed it, I wrote a lot of this kind of thing:

var arr1 = ["Alpha","Beta","Gamma","Delta"];

function aToB(arr){
    for(var i =0 ;i < arr.length; i++) {
        arr2.push(arr[i].replace(/a/gi,"b");
    }
}

var arr2 = aToB(arr1)

Enter fullscreen mode Exit fullscreen mode

The result:

[ 'blphb', 'Betb', 'Gbmmb', 'Deltb' ]

It's fine and it works, but there is a better way. This function takes an array, and replaces


s with

 ```b```

s. Javascript has a built-in method that takes care of the redundant bits for you:



Enter fullscreen mode Exit fullscreen mode

var arr1 = ["Alpha","Beta","Gamma","Delta"];
arr2 = arr1.map(function(a){return a.replace(/a/gi,"b")});






```array.map```

 is a great solution if you need to do some sort of transformation on an array. It can be something like changing all the a's to be b's, or it can be something more useful like parsing sets of data. Consider this function that parses and returns dates :



Enter fullscreen mode Exit fullscreen mode

var dates = ["2017-04-01","2017-04-07","2013-01-22",]

function pDates(a){
for(var i =0; i < a.length; i++){
a[i] = new Date(a[i].split("-"));
}
return a;
}



The results:


```[ Sat Apr 01 2017 00:00:00 GMT-0700 (PDT),
  Fri Apr 07 2017 00:00:00 GMT-0700 (PDT),
  Tue Jan 22 2013 00:00:00 GMT-0800 (PST) ]```




It's a fine function but we can accomplish it more compactly, and without potential pitfalls (like trying to figure out if your iterator is going to miss a key):



Enter fullscreen mode Exit fullscreen mode

dates = dates.map(function(d){
return new Date(d.split("-"))
});



Is it that much of a difference? No, but it gives the same result. If you're familiar with using

 ```map```

 you can save yourself some time and trouble. On top of that it's a lot quicker to _read_ and that's a favor you're doing for the _next_ developer.

If you've not spent the time becoming familiar with some of the native implementations available in the Javascript specification, there's a lot to be gained by perusing and understanding how they work. I recommend spending some time at [MDN](https://developer.mozilla.org/en-US/) perusing the [Javascript reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference).

Enter fullscreen mode Exit fullscreen mode

Top comments (11)

Collapse
 
revent profile image
Roberts Guļāns

one could even change this:
arr2 = arr1.map(function(a){return a.replace(/a/gi,"b")});
to ES6 syntax:
arr2 = arr1.map(a => a.replace(/a/gi,"b"))

Collapse
 
joeymink profile image
Joey Mink

Somewhat related -- if you're lazy like me, you might use map() simply to act on each item in the array (ignoring the fact that map creates a returns a new array). Don't do that! Use forEach() 👍

Collapse
 
mantasmarcinkus profile image
Mantas Marcinkus

Just an addition to your article that I missed. One of the most important .map properties is that it returns a new array, it doesn't mutate current array. This is particularly useful in React/Redux, or where you want your objects to safely persist state.

Collapse
 
zakius profile image
zakius

I always find explicit for (or at least foreach) much are readable than all the different syntaxes of map appearing in different languages. Often It's better to explicitly write line or two more than to use fancy shorthands, especially if the codebase might get visited by juniors

Collapse
 
revent profile image
Roberts Guļāns

its more apis to learn (map, find, some, every, filter, reduce) than just for-loop, but one you have done that and know where and why which function to use, value is huge.

Code speaks to you and just by reading one word you know intent what is supposed to happen. for-loop lacks such expressiveness, one have to dig into for-loop's body to understand why loop exists, what is doing.

And immutability on its own makes code so much easier to understand.

Fact that juniors also works on a project shouldn't sacrifice projects quality

Collapse
 
maxart2501 profile image
Massimo Artizzu

On the contrary, juniors should get to know the FP side of languages like JavaScript as soon as possible. And the concepts behind it, like purity and immutability.

Collapse
 
llexical profile image
Lizzie

Really important: Array.[map | find | some | every | filter | reduce]() key functions to handling arrays in easy, readable ways. It saves you a lot of hassle and a lot of ugly loops!

Collapse
 
maxart2501 profile image
Massimo Artizzu

Another addition is that methods like map (and also forEach, every...) do not iterate over empty items. For example: new Array(5).forEach(console.log) doesn't print anything, so beware!

Note: it doesn't mean they don't iterate over undefined values. Just empty, pristine slots that hasn't been assigned a value yet.

So if you're thinking you could use new Array(n).forEach(fn) to execute fn n times, you're out of luck. Also, that would generate a throwaway array, so it's sub-optimal. Use for for that.

(There's also this trick: Array.from({ length: 3 }).forEach(console.log). It works, but it's kind of jarring. Again, I don't recommend doing that.)

Others already pointed out that map returns a new array. Good for immutability!

Collapse
 
tiffany profile image
tiff

Just so I'm clear as a junior: map() does not mutate an array just makes a new one?

Collapse
 
aeiche profile image
Aaron Eiche

Correct, array.map returns a new array that will not mutate your old one.

You could conceivably alter your original array while in the function executing on a key, but then you're out of the realm of using


 anyway.
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tiffany profile image
tiff

I was about to ask if you meant a key as in an index in the array. I forgot that Arrays are objects in JavaScript, as pretty much everything else. But still, I am not sure what you mean by the function executing on a key.