两个数组取交集

function fn(a, b) {
  const result = [];
  const map = a.reduce((obj, item) => {
    obj[item] ? obj[item]++ : obj[item] = 1;
    return obj;
  }, {});
  b.forEach(item => {
    if (map[item] && map[item] > 0) {
    result.push(item);
    map[item]--
  }
  })
  return result
}

fn([1,1,2,3,4,2,5],[1,6,5,3,7,4,2,1,1,2,2,1,6]);

posted @ 2019-08-01 11:45  Jay_Lo  阅读(291)  评论(0编辑  收藏  举报