在数组JavaScript中查找重复最少的项目
我们需要编写一个JavaScript函数,该函数接受一个可能包含一些重复值的文字数组。
该函数应返回所有元素重复最少次数的数组。
例如-如果输入数组是-
const arr = [1,1,2,2,3,3,3];
那么输出应该是-
const output = [1, 2];
因为1和2重复的次数最少(2)
示例
const arr = [1,1,2,2,3,3,3];
const getLeastDuplicateItems = (arr = []) => {
const hash = Object.create(null);
let keys, min; arr.forEach(el => {
hash[el] = hash[el] || {
value: el, count: 0 };
hash[el].count++; });
keys = Object.keys(hash);
keys.sort(function (el, b) {
return hash[el].count - hash[b].count; });
min = hash[keys[0]].count;
return keys. filter(el => {
return hash[el].count === min;
}).
map(el => {
return hash[el].value;
});
}
console.log(getLeastDuplicateItems(arr));输出结果
控制台中的输出将是-
[ 1, 2 ]
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志