【问题标题】:How do I calculate the mode of an array - JavaScript? [duplicate]如何计算数组的模式 - JavaScript? [复制]
【发布时间】:2020-08-06 07:04:34
【问题描述】:

我正在编写一个代码来查找数组中一组数字的模式 (differenceArr)。我几乎破解了它,除了有一个问题。让我向您展示我到目前为止的代码,以便您理解:



  
var mapping = {};
var counter = 0;
for(var i = 0;i < differenceArr.length; i++){
    if (!mapping[differenceArr[i]]) mapping[differenceArr[i]] = 0;
    mapping[differenceArr[i]] += 1;
}
var z;
var toValidateModeJSONObj = mapping;
var max_of_difarray = Math.max.apply(Math, differenceArr);
var howManyActuallyExist = -1;
var modeArray = [];
for(var n = 0; n< max_of_difarray; n++){
   
    var exists = toValidateModeJSONObj[differenceArr[n].toString()]; 
    if(exists == undefined){
        exists = false;
        
    }else{
        howManyActuallyExist++;
       modeArray[howManyActuallyExist] ={theNumber: differenceArr[n].toString(), theValue: exists};
    }
console.log(JSON.stringify(modeArray));

现在我在modeArray 中拥有了所有内容,我必须在modeArray 中获取最大的theValue,然后我必须在变量中获取模式以便我可以返回它。我怎么做?谁有任何工作代码sn-ps?

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    试试这个:)

    const getMode = (items) => {
      // Go through the array
      
      if (items.length === 0) return -1 // error
      
      const store = {}
      let maxCount = 0;
      let maxIndex = -1;
      
      items.forEach((item, index) => {
        if (!store[item]) {store[item] = 0}
        
        // update value
        store[item] += 1
        
        if (store[item] > maxCount) {
          maxIndex = index
          maxCount = store[item]
        }
      })
      
      // NOTE: this code does not consider if there are two modes.
      
      return items[maxIndex]
    }
    
    // ==========================
    
    
    const getModeMoreThanOne = (items) => {
      // Go through the array
      
      if (items.length === 0) return -1 // error
      
      const store = {}
      let maxCount = 0
      let maxIndex = -1
      
      items.forEach((item, index) => {
        if (!store[item]) {store[item] = 0}
        
        // update value
        store[item] += 1
        
        if (store[item] > maxCount) {
          maxIndex = index
          maxCount = store[item]
        }
      })
      
      
      const modes = Object.keys(store).filter(key => store[key] === maxCount)
    
      return modes
    }
    
    
    getMode("abcdefababa".split("")) // 'a'
    
    getModeMoreThanOne("abcdefabbaba".split("")) // ['a', 'b']
    

    【讨论】:

      猜你喜欢
      • 2013-01-17
      • 2019-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      相关资源
      最近更新 更多