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?
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.
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.
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}`)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With