loading...

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

aeiche profile image Aaron Eiche ・2 min read

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)

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:



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 :



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):



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).

Posted on by:

aeiche profile

Aaron Eiche

@aeiche

Infotainment developer at Jaguar Land Rover. Robotics and electronics enthusiast in my free time.

Discussion

markdown guide
 

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"))

 

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() 👍

 

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!

 

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.

 

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

 

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.

 

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

 

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!

 

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

 

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.
 

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.