极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。

# 实现 intersection,取数组交集

更多描述

类似 lodash.intersection,有以下测试用例

//=> [2]
intersection([2, 1], [2, 3]);

//=> [1, 2]
intersection([1, 2, 2], [1, 2, 2]);

//=> [1, 2]
intersection([1, 2, 2], [1, 2, 2], [1, 2]);

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 673 (opens new window)

const intersection = (...list) => {
  const result = list.reduce((x, y) => x.filter((i) => y.includes(i)));
  return [...new Set(result)];
};

Author

回答者: Kiera569 (opens new window)

const intersection = (...list) =>
  list.reduce((a, b) => [...new Set(a.filter((item) => b.includes(item)))]);
function intersection(...args) {
  if (args.length === 0) return [];
  for (let i = 0; i < args.length; i++) {
    if (!Array.isArray(args[i])) {
      args[i] = [args[i]];
    }
  }
  if (args.length === 1) return [...new Set(args[0])];
  let index = 1;
  let sameArr = args[0];
  while (index < args.length) {
    let tempArr = [];
    for (let i = 0; i < args[index].length; i++) {
      if (sameArr.includes(args[index][i])) {
        tempArr.push(args[index][i]);
      }
    }
    sameArr = tempArr;
    if (sameArr.length === 0) return [];
    index += 1;
  }
  return [...new Set(sameArr)];
}

Author

回答者: Asarua (opens new window)

const intersection = (...args) => [
  ...new Set(args.reduce((prev, next) => prev.filter((v) => next.includes(v)))),
];

emm,绕了一圈绕回来了

@Asarua 去重一下,看第二个示例,而且还有可能是多个数组呀,我去补一下测试用例

Author

回答者: Asarua (opens new window)

@Asarua 去重一下,看第二个示例

已改

function intersection() {
  const arrays = [].slice.call(arguments, 0);
  const result = arrays.reduce(function (acc, arr) {
    return acc.filter((v) => arr.indexOf(v) !== -1);
  });
  return result.reduce((acc, c) => {
    if (acc.indexOf(c) === -1) {
      acc.push(c);
    }
    return acc;
  }, []);
}
Last Updated: 11/27/2021, 6:11:48 PM