找出数组中重复次数最少的项 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 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP