Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

20、多个数组求交集 #20

Open
shengq666 opened this issue Jul 28, 2020 · 1 comment
Open

20、多个数组求交集 #20

shengq666 opened this issue Jul 28, 2020 · 1 comment

Comments

@shengq666
Copy link
Owner

No description provided.

@shengq666
Copy link
Owner Author

shengq666 commented Jul 28, 2020

1、合并数组 循环判断数组中的值出现的次数

function ar() {
    let args = [...arguments]
    let tmpArr = []
    let returnArr = []
    for(let i=0;i<args.length;i++) {
        tmpArr = [...tmpArr,...args[i]]
    }
    for(let i=0;i<tmpArr.length;i++) {
        let count = 0
        for(let j=0;j<tmpArr.length;j++) {
            if(tmpArr[i] === tmpArr[j]) {
                count++
            }
            if(count === args.length && returnArr.indexOf(tmpArr[i])<0 ) {
              returnArr.push(tmpArr[i])  
               break
            }
        }
    }
    return returnArr
}

2、reduce 结合 filter,累加后的数组对当前项进行过滤

function intersect() {
    let args = [...arguments]
    if(args.length === 0) {
        return []
    }
    if(args.length === 1) {
        return args[0]
    }
    return args.reduce((accu,curr)=>{
        return accu.filter(v => curr.indexOf(v) > -1);
    })
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant