-1

I am making a code that finds the mode of a set of numbers in an array (differenceArr). I almost cracked it, except there is one problem. Let me show you my code so far so you can understand:



  
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));

Now that I have everything in modeArray, I have to get which one has the biggest theValue in modeArray, and then I have to get the mode in a variable so I can return it. How do I do that? Anyone have any working code snippets?

anonsaicoder9
  • 107
  • 1
  • 12

1 Answers1

0

Try this out :)

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']
Ishan Joshi
  • 116
  • 6