DEV Community

Discussion on: JavaScript Quick Tip: Quickly Filter Out All Falsy Values From An Array

Collapse
 
aminnairi profile image
Amin

Hi Oliver and thanks for your interesting well written article!

In some of my project where I need it, I like to create a filterMap function which allows me to map values to something else, just like we would with the map and get only truthy values in the JavaScript sense.

const filterMap = (callback, items) => {
  return items.reduce((oldItems, item) => {
    const newItem = callback(item);

    if (newItem) {
      return [...oldItems, newItem];
    }

    return oldItems;
  }, []);
};

const getElementById = (identifier) => {
  if (Math.random() > 0.5) {
    return `Element#${identifier}`;
  }

  return null;
};

const identifiers = [
  "paragraph",
  "title",
  "users",
  "answers"
];

const elements = filterMap(getElementById, identifiers);

console.log(elements);
// [ 'Element#paragraph', 'Element#users', 'Element#answers' ]
Enter fullscreen mode Exit fullscreen mode

The pro of using reduce instead of map combined with filter is mainly performance since the reduce call will do one pass where the map and filter will do it in two passes.

Often, this is a recurring pattern and when I see that I am doing a mapping and a filtering, I know that I can do it in one reduce.

Collapse
 
oliverjumpertz profile image
Oliver Jumpertz

You are right but it can hurt readability.

Try immutable-js, it has lazy pipeline sequences which work through transducers. No matter how many operations you pipe, only one pass. ☺️