1.使用map存储对应的数据,key是数据,value是出现的次数
function GetArrayMost(arr){
var arrMap = new Map();
var key = arr[0],
value = 1;
arr.forEach((item, index) => {
if (arrMap.get(item) !== undefined) {
let num = arrMap.get(item);
arrMap.set(item, ++num);
} else {
arrMap.set(item, 1);
}
if (arrMap.get(item) > value) {
key = item;
value = arrMap.get(item);
}
});
return [key,value];
}
//测试
var arr = [1,2,3,4,5,6,7,1,12,3,3,3,3,3,3,3,3,3]
console.log(
"次数最多的元素为:",
GetArrayMost(arr)[0],
",次数为:",
GetArrayMost(arr)[1]
);
//次数最多的元素为: 3 ,次数为: 10
2.有点问题
function GetArrayMost__reduce(arr){
var obj = arr.reduce((p,n) => (p[n]++ || (p[n] = 1),
(p.max = p.max >= p[n]? p.max: p[n]),
(p.key = p.max >= p[n]? p.key: n),p),{});
return obj;
}
console.log(
"次数最多的元素为:",
GetArrayMost__reduce(arr).key,
",次数为:",
GetArrayMost__reduce(arr).max
);
3.
function GetArrayMost__reduce(arr) {
var maxElement;
var maxNum = 1;
var obj = arr.reduce(
(p, n) => {
p[n]? p[n]++: p[n] = 1;
if(p[n] > maxNum){
maxElement = n;
maxNum++;
}
return p;
},
{}
);
return [maxElement, maxNum];
}
console.log(GetArrayMost__reduce(arr));
console.log(
"次数最多的元素为:",
GetArrayMost__reduce(arr)[0],
",次数为:",
GetArrayMost__reduce(arr)[1]
);