在数组中查找最少重复项 JavaScript
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个 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 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

