Skip to content Skip to sidebar Skip to footer

Array Filter And Map At The Same Time?

I feel like an idiot, but I need to filter my array, and then map those values, but thats O(2N) and it would make more sense to do it all in O(N) but I can't find a stock Array.pro

Solution 1:

How about Array.prototype.reduce()?

arr.reduce((newArr, item) => {
    if (!!item.revenue) {
        newArr.push(item.revenue)
    }
    return newArr
}, []);

Solution 2:

flatMap covers this use case - filtering and mapping at the same time:

arr.flatMap(item => item.revenue || [])

Post a Comment for "Array Filter And Map At The Same Time?"