3 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超10個(gè)贊
如果你需要使用 Map,那么你可以這樣做:
const highestFreq = (array) => {
let myMap = new Map();
for( let i = 0; i < array.length; i++ ) {
if (myMap[array[i]]) myMap[array[i]]++;
else myMap[array[i]] = 1;
}
return myMap;
}
const myArray = [101, 104, 108, 108, 111, 119, 119, 119];
const myMap = highestFreq(myArray);
console.log(myMap);
myMap 包含鍵值對(duì),其中鍵是給定數(shù)組中的唯一元素,映射值是它們的出現(xiàn)次數(shù)。

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
使用對(duì)象方式,您可以實(shí)現(xiàn)如下:
var highestFrequency = (array) => {
var occurenceStored = {};
for (var i = 0; i < array.length; i++){
if (occurenceStored[array[i]]){
occurenceStored[array[i]] = occurenceStored[array[i]]+1;
} else{
occurenceStored[array[i]]=1;
}
}
console.log(occurenceStored);
}

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
假設(shè)您只想要最頻繁的值(如果有兩個(gè)具有相同頻率的不同值怎么辦?):
每個(gè)值增加一個(gè)計(jì)數(shù)器
迭代時(shí),如果計(jì)數(shù)器大于您最大的計(jì)數(shù)器,則改為最大。
const highestFreq = arr => {
const best = { value: 0, n: 0 } // what to do if empty array ??
arr.reduce((m, el) => {
const counter = (m.get(el) || 0) + 1
if (counter > best.n) {
best.value = el
best.n = counter
}
return m.set(el, counter)
}, new Map())
return best // or compute your frequency: best.n / arr.length
}
console.log(highestFreq([101, 104, 108, 108, 111, 119, 119, 119]))
添加回答
舉報(bào)