Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: Array.map don't add to array

I have some data I'd like to transform using Array.prototype.map. However in the map function there is a chance of an error being thrown by an external function call. I'd like to catch this error and not add that particular object to the returned array. Currently I'm just returning undefined and then using Array.prototype.filter to clear out the undefined values, but this seems like a dirty way to do it.

To clarify, I'm looking for this functionality:

['apple','pear','banana', 'peach'].map(function(fruit){
     if (fruit === 'apple') {
         return undefined;
     }
     return 'I love to eat ' + fruit;
});
// ['I love to eat pear', 'I love to eat peach', 'I love to eat banana']

Any existing implementatons of this? Am I just going about this the wrong way?

like image 770
jtmarmon Avatar asked Nov 24 '14 17:11

jtmarmon


People also ask

Does array map change the original array?

map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.

Does map work on arrays?

The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally map() method is used to iterate over an array and calling function on every element of array.


1 Answers

A more readable way would be;

['apple','pear','banana', 'peach'].filter(function(fruit) {
    return fruit === 'apple';
}).map(function(fruit) {
    return 'I love eating ' + fruit; 
})

With arrow functions & template strings;

['apple','pear','banana', 'peach']
    .filter(fruit => fruit === 'apple')
    .map(fruit => `I love eating ${fruit}`)
like image 162
Renato Gama Avatar answered Sep 27 '22 20:09

Renato Gama