在 JavaScript 中查找包含至少一个元素的最小子数组的最简单方法是什么?



在JS中查找包含至少一个元素的最小子数组的最简单方法是什么?

例如,对于[1,2], [1,3], [4]结果应为[1,4]的数组,它包含来自第一个和第二个数组的 1,以及来自第三个数组的 4

  1. 导航所有数字,构建一个counts对象,其中数字作为键和值作为它们在数组中出现的频率。
  2. 在数组上使用map,每个子数组找出具有最大计数的项目(更频繁的项目(。
  3. 使用Set删除重复条目以获取最小的子数组。

const smallsub = (arr) => {
const counts = {};
arr.flat().forEach((num) => (counts[num] = (counts[num] ?? 0) + 1));
const items = arr.map((nums) =>
nums.reduce((max, num) => (counts[num] > counts[max] ? num : max))
);
return [...new Set(items)];
};
const arr = [[1, 2], [1, 3], [4]];
console.log(smallsub(arr));

最新更新