1

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.

2
  • Use a reduce function. Commented Dec 7, 2019 at 3:17
  • 2
    Unless there is a measurable reason to seek an optimization filter().map() is good — it's very readable and easy to understand. Commented Dec 7, 2019 at 3:21

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.