The transduce function creates a new array of elements passing a filter and resulting from a map.
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)
);
}
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']
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']