如何使用函数式编程过滤到多条路径 [英] How to filter to multiple paths using functional programming

查看:45
本文介绍了如何使用函数式编程过滤到多条路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下伪代码:

let array = getData();
array.filter(x => condition1(x)).doSomething1...
array.filter(x => condition2(x)).doSomething2...
array.filter(x => condition3(x)).doSomething3...

显然,这是无效的,因为它将数组重复3次.

Obviously this is not efficient because it iterates the array 3 times.

我想知道我是否可以做类似的事情:

I was wondering if I there is a way to do something like:

array.filterMany([
    x => condition1(x).doSomething1...,
    x => condition2(x).doSomething2...,
    x => condition3(x).doSomething3...
])

这样数组只能被迭代一次?

So that the array gets iterated only once?

推荐答案

您可以使用数组缩减功能.

You can use array reduce functionality.

例如:

    const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    
    const split = arr.reduce(([odd, even], current) => {
        if (current % 2 === 0) {
           even.push(current);
        } else {
           odd.push(current);
        }
    
        return [odd, even];
    }, [[], []]);
    
    console.log('Odd / Even', split);

这篇关于如何使用函数式编程过滤到多条路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆