Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore.js _.map function : skip a value

I am trying to use underscore.js _.map function on an array of objects, to get an array with a property of each object. That's the usual scenario, so :

var finalArray = _.map(myArray, function(obj) {     return obj.myProperty; }); 

But in some cases I need that nothing be added in the array. It could be something like :

var finalArray = _.map(myArray, function(obj) {     if (!obj.ignore) {         return obj.myProperty;     } }); 

The result of this is that an undefined value is pushed into the array, which is not the same as not pushing anything at all.

Is there a way for the map function not to push a value, or do I need to post-process my finalArray to remove the unwanted undefined's?

like image 396
foucdeg Avatar asked Jun 12 '15 13:06

foucdeg


People also ask

What is _ in Map JavaScript?

js. Lodash helps in working with arrays, collection, strings, objects, numbers etc. The _. map() method creates an array of values by running each element in collection through the iteratee.

What is the use of underscore in JavaScript?

Underscore ( _ ) is just a plain valid character for variable/function name, it does not bring any additional feature. However, it is a good convention to use underscore to mark variable/function as private. You can check Underscore prefix for property and method names in JavaScript for some previous discussion.

Is underscore JS still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.


2 Answers

you should use _.filter() before _.map()

var filteredArray = _.filter(myArray,function(obj) {      return !obj.ignore; });  var finalArray = _.map(filteredArray, function(obj) {     return obj.myProperty; }); 
like image 185
couettos Avatar answered Sep 20 '22 08:09

couettos


You could use reduce:

myArray.reduce(function (acc, obj) {     if (!obj.ignore) {         acc.push(obj.myProperty);     }     return acc; }, []); 

or with lodash:

_.reduce(myArray, function (acc, obj) {   if (!obj.ignore) {     acc.push(obj.myProperty);   }   return acc; }, []); 
like image 44
Thomas Eschemann Avatar answered Sep 19 '22 08:09

Thomas Eschemann