高级前端手写代码【Q655】实现 intersection,取数组交集

实现 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

Author 回答者: shfshanyue

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

Author 回答者: Kiera569

const intersection = (...list) =>
  list.reduce((a, b) => [...new Set(a.filter((item) => b.includes(item)))]);

Author 回答者: heretic-G

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

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

emm,绕了一圈绕回来了

Author 回答者: shfshanyue

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

Author 回答者: Asarua

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

已改

Author 回答者: haotie1990

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;
  }, []);
}

Author 回答者: rujptw

// 取数组交集

/**
 *
 *
 * @param  {...any} arr 剩余数组
 * @returns
 * 思路:
 * 1.设置两个数组,一个存放未重复的数组元素,一个存放已重复的数组元素
 * 2.在总的数组的循环中,如果数组元素在未重复数组中,又出现一次,则将其推入已重复数组
 * 3.使用Set,去除多余的元素,使用Array.from将Set实例转化为数组,并返回
 */
function intersection(...arr){
  let filterArr = [];
  let duplicateArr = []
  let sumArr = [].concat(...arr)
  sumArr.forEach(element => {
    if(!filterArr.includes(element)){
      filterArr.push(element)
    }else{
      duplicateArr.push(element)
    }
  });
  return Array.from(new Set(duplicateArr));
}

//=> [2]
console.log('intersection([2, 1], [2, 3]);: ', intersection([2, 1], [2, 3]));

//=> [1, 2]
console.log('intersection([1, 2, 2], [1, 2, 2]): ', intersection([1, 2, 2], [1, 2, 2]));

//=> [1, 2]
console.log('intersection([1, 2, 2], [1, 2, 2], [1, 2]): ', intersection([1, 2, 2], [1, 2, 2], [1, 2]));

Author 回答者: Hazel-Lin

const intersection = (...arr) => [
  ...new Set(
    arr.reduce((pre, cur) => pre.filter((item) => cur.includes(item))),
  ),
];
// [ 2, 3 ]
console.log(intersection([2, 3, 3], [2, 2, 3, 1], [2, 3, 1, 5]));