Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason to use lodash / underscore .map() function?

In my current project I can see many _.map() usages almost identical like the following example:

var a = [1,2,3,4,5,6,7,8];
var lodashMap = _.map(a, i => {
  if (i < 5) return i-1;
});

And I can't see any reason to not use just built-in Array.map() method like this:

var arrayMap = a.map(i => {
  if (i < 5) return i-1;
});

I know none of these mutates original array and made sure that the result is exactly the same: https://codepen.io/anon/pen/xqPMNQ

Also as we are using Typescript, lodash version loses the i parameter type, so I want to use Array.map() instead. Is there any difference I'm not aware of between Array.map and _.map()?

like image 520
Daniel Kucal Avatar asked Mar 17 '17 15:03

Daniel Kucal


Video Answer


1 Answers

For the purposes of the examples you have there, there's no effective difference between the two options and you're just as well off using a.map().

However, there are some differences between _.map and Array#map.

One is that it can be called directly on array-like objects. (To do so with Array#map requires either attaching the function to the object and then calling it, or using the awkward approach with .call().)

Example:

var mapped = _.map(document.getElementsByTagName('li'), el => el.textContent);

console.log(mapped);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<ul><li>A</li><li>B</li><li>C</li></ul>

You can also use _.map on objects that are not array-like. This is something that Array#map can't do at all.

Example:

var myObj = { a: 1, b : 2 };
var mapped = _.map(myObj, (val, key) => key + val);

console.log(mapped);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

It can also be used on null without throwing an error (it just returns an empty array). Depending on how you look at it, you may consider this a good thing or a bad thing, but it's a notable difference from the native .map.

Example:

var myObj = null;
var mapped = _.map(myObj, (val, key) => key + val);

console.log(mapped);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Aside from that, there's just the benefit of uniformity if you're combining it with a lot of other lodash/underscore functions.

Also, _.map can be used in an underscore/lodash chain.

Example:

var values = [{ value: 10 }, { value: 2 }, { value: 13 }, { value: 7 }];
var result =  _.chain(values)
                .map(_.property('value'))
                .filter(v => v > 5)
                .sortBy()
                .value();
                
console.log(result);
  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
like image 140
JLRishe Avatar answered Sep 28 '22 03:09

JLRishe