Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array filter and map at the same time?

Tags:

javascript

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.prototype function

array.filter(item => !!item.revenue).map(item => item.revenue)

I can always write my own method but it would be best to use the performance optimized Array.prototype ones, if there is one

like image 744
neaumusic Avatar asked Sep 24 '26 00:09

neaumusic


1 Answers

How about Array.prototype.reduce()?

arr.reduce((newArr, item) => {
    if (!!item.revenue) {
        newArr.push(item.revenue)
    }
    return newArr
}, []);
like image 195
Phil Avatar answered Sep 26 '26 14:09

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!