取两个重复数组的交集

const set_intersection = (set1, set2) => {
  if (set1.size > set2.size) {
    return set_intersection(set2, set1);
  }
  const intersection = new Set();
  for (const num of set1) {
    if (set2.has(num)) {
      intersection.add(num);
    }
  }
  return [...intersection];
};

var intersection = function (nums1, nums2) {
  const set1 = new Set(nums1);
  const set2 = new Set(nums2);
  return set_intersection(set1, set2);
};

new set 不能用 for 循环 取不到具体数值

取它们的并集

编写一个函数计算多个数组的交集

Array.slice() 该方法并不会修改数组,而是返回一个子数组。如果想删除数组中的一段元素,应该使用方法 Array.splice().

/**

  • 数组扁平化、去重、排序 */ const list = [1, [2, 3, 8], [3, 6, 4], [5, [6, 7, [8, 1, 2]]]];

/====== 扁平化 ======/

/====== 数组去重 ======/

/====== 排序 ======/ // 冒泡排序

const flatArr = flat(list); console.log('flatArr: ', flatArr); // [1, 2, 3, 8, 3, 6, 4, 5, 6, 7, 8, 1, 2]

const uniArr = unique(flatArr); console.log('uniArr: ', uniArr); // [1, 2, 3, 8, 6, 4, 5, 7]

const sortArr = bubbleSort(uniArr); // [1, 2, 3, 4, 5, 6, 7, 8] console.log('sortArr: ', sortArr);

最后更新于

这有帮助吗?