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

比较两数组差异 (Diff Two Arrays) #81

Open
Cosen95 opened this issue Mar 10, 2020 · 2 comments
Open

比较两数组差异 (Diff Two Arrays) #81

Cosen95 opened this issue Mar 10, 2020 · 2 comments

Comments

@Cosen95
Copy link
Owner

Cosen95 commented Mar 10, 2020

No description provided.

@lovefishs
Copy link

type ISimpleArray = Array<number | string>

function difference(a: ISimpleArray, b: ISimpleArray) {
  const long = a.length > b.length ? a : b
  const short = a.length > b.length ? b : a

  return long.filter((item) => {
    return !short.includes(item)
  })
}

@Cosen95
Copy link
Owner Author

Cosen95 commented Mar 25, 2020

基本解法(循环)

function diff(arr1, arr2) {
    // 用 firstArr 和 secondArr 来表示传入的参数,均为数组
    function getDiff (firstArr, secondArr) {
        // 设置一个变量用于暂存结果
        var result = [];

        // 逻辑思路是,遍历 firstArr,然后与 secondArr 比较
        for (var i = 0; i< firstArr.length; i++) {
            if (!secondArr.includes(firstArr[i])) {
                result.push(firstArr[i]);
            }
        }

        // 这个 result 并不是最终的结果。我们需要对传入的参数操作两次,然后把两次的结果合并起来
        return result;
    }

    return getDiff(arr1, arr2).concat(getDiff(arr2, arr1));
}

中级解法(filter)

function diff(arr1, arr2) {
    return arr1.filter(e => !arr2.includes(e) ).concat(
        arr2.filter(e => !arr1.includes(e))
    );
}

一行搞定(先合并,再过滤)

function diff(arr1, arr2) {
    return arr1.concat(arr2).filter(e => !arr1.includes(e) || !arr2.includes(e));
}

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

No branches or pull requests

2 participants