Is it possible to combine Underscore’s filter and map? I currently have two separate function calls, but I’m wondering if I can make them more efficient by combining them into a single call, somehow.
Basically I have an array of country names – I want to filter them using a regex, then map the filtered results to an array of DataItem objects. This is my current code:
var filteredData = _.filter(allCountries, function(n, i){
var re = RegExp("^" + searchString, "i");
if (re.exec(n['country'].toLowerCase()) !== null) {
return true;
}
});
var mappedData = _.map(filteredData, function(n, i){
return new DataItem(i, n['name'], n['budget']);
});
Any other tips for improved efficiency would also be gratefully received.
You can use
eachinstead:Also note that you don’t need a regular expression just to find out if a string starts with another one.