filter and map in same iteration

Viewed 2124

I have this simple situation where I want to filter and map to the same value, like so:

 const files = results.filter(function(r){
      return r.file;
    })
    .map(function(r){
       return r.file;
    });

To save lines of code, as well as increase performance, I am looking for:

const files = results.filterAndMap(function(r){
  return r.file;
});

does this exist, or should I write something myself? I have wanted such functionality in a few places, just never bothered to look into it before.

8 Answers

Arrays are iterable objects, and we can apply all needed operations in just one iteration.

Example below does such single iteration, using iter-ops library:

import {pipe, filter, map} from 'iter-ops';

const i = pipe(
    results,
    filter(r => !!r.file),
    map(m => m.file)
);

console.log('files:', [...i]);
Related