array.filter with async/await

13 May 2021 in TIL

I can never remember how to filter arrays in JavaScript when I need to use await to run a method.

The answer is that array.filter does not support async, so we have to use array.reduce instead. Here's an example of how it works:

javascript
let values = ["another", "word", "here"];
values = await values.reduce(async (acc, v) => {
const result = await hasFourLetters(v);
// If our async method didn't return true, return the current list
// *without* this new entry
if (!result) {
return acc;
}
// Otherwise add this value to the list
return (await acc).concat(run);
}, []);
// values = ["word", "here"]