Reputation: 12209
In Javascript, Array.filter() takes an array and filters it down based on a certain criteria.
const a = [1,2,3,4,5].filter(el => el > 3);
console.log(a);
Result: [4,5]
Array.map() takes an array and returns a new array of equal length, usually mutating the original's elements in the process.
const a = [1,2,3,4].map(el => el + 10);
console.log(a);
Result: [11,12,13,14,15]
My question is, besides combining the two functions like this:
let a = [1,2,3,4,5].filter(el => el > 3).map(el => el + 10);
console.log(a);
is there an efficient way to filter and mutating an array, that doesn't involve multiple lines of code like most Array.forEach
, for
, and for..in
routines? I know that Array.filter().map()
is pretty efficient, I'm just wondering if it can be further streamlined.
Upvotes: 1
Views: 273
Reputation: 48600
Use Array.prototype.reduce
to take care of filtering and mapping all at once.
let a = [1,2,3,4,5].reduce((arr, el) => el > 3 ? arr.concat(el + 10) : arr, []);
console.log(a);
You could also make your own mapIf
polyfill function.
// Reduce Only
if (Array.prototype.mapIf === undefined) {
Array.prototype.mapIf = function(predicateFn, applyFn) {
return this.reduce((ref, el) => predicateFn(el) ? ref.concat(applyFn(el)) : ref, []);
};
}
// Filter + Map
if (Array.prototype.mapIf === undefined) {
Array.prototype.mapIf = function(predicateFn, applyFn) {
return this.filter(predicateFn).map(applyFn);
};
}
let a = [1,2,3,4,5].mapIf(el => el > 3, el => el + 10);
console.log(a);
Upvotes: 2