在数组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 ]
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便