Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Last active May 21, 2019 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathantneal/11fbcff71f6594d0d186187837c17919 to your computer and use it in GitHub Desktop.
Save jonathantneal/11fbcff71f6594d0d186187837c17919 to your computer and use it in GitHub Desktop.
JavaScript Array Transduce and FlatMap Alternative

transduce

The transduce function creates a new array of elements passing a filter and resulting from a map.

Implementation

function transduce (filterCallbackFn, mapCallbackFn, ...transduceArgs) {
  return Array.prototype.reduce.call(
    this,
    (acc, ...reduceArgs) => filterCallbackFn.call(this, ...reduceArgs, ...transduceArgs)
      ? acc.concat(mapCallbackFn.call(this, ...reduceArgs, ...transduceArgs))
    : acc,
    Array.prototype.slice.call(this, 0, 0)
  );
}

Usage

Return a new array of available movie titles:

[
  { title: 'Star Wars: Return of the Jedi', year: 1980, isAvailable: true },
  { title: 'Return to Oz', year: 1985, isAvailable: true },
  { title: 'Lord of the Rings: The Return of the King', year: 2003, isAvailable: true },
  { title: 'Star Wars: The Rise of Skywalker', year: 2019, isAvailable: false }
]::transduce(
  movie => movie.isAvailable,
  movie => movie.title
); // ['Star Wars: Return of the Jedi', 'Return to Oz', 'Lord of the Rings: The Return of the King']

FlatMap Alternative

The flatMap function can be used to filter items during an Array map.

[
  { title: 'Star Wars: Return of the Jedi', year: 1980, isAvailable: true },
  { title: 'Return to Oz', year: 1985, isAvailable: true },
  { title: 'Lord of the Rings: The Return of the King', year: 2003, isAvailable: true },
  { title: 'Star Wars: The Rise of Skywalker', year: 2019, isAvailable: false }
].flatMap(
  movie => movie.isAvailable ? [movie.title] : []
); // ['Star Wars: Return of the Jedi', 'Return to Oz', 'Lord of the Rings: The Return of the King']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment