Skip to content
Advertisement

How can I return the mode that appeared first in an array in Javascript?

I want to create a function that will return the number with highest frequency(mode). For example: if array contains [10, 4, 5, 2, 4] the output should be 4. If there is more than one mode, I want to return the one that appeared in the array first (ie. [10,2,5, 4, 5, 2, 4] should return 2 because it appeared first. If there is no mode, I want to return -1. The array will not be empty. Below is my attempt

function Mode(arr){
    if(arr == undefined || arr.length == 0){
        return
    }
    const number_to_frequency = {};
    let number_with_overall_highest_frequency = 0;
    let overall_highest_frequency = 0;

    for(index in arr) {
        const number = arr[index];
   
        if(number_to_frequency[number]) {
            number_to_frequency[number] += 1;
        } else {
            number_to_frequency[number] = 1;
        }
   
        let updated_frequency = number_to_frequency[number]
   
        if(overall_highest_frequency < updated_frequency) {
            number_with_overall_highest_frequency = number;
            overall_highest_frequency = updated_frequency;
        }
   
  }
 
  if(overall_highest_frequency == 1){
      return -1
  }
  return number_with_overall_highest_frequency;
};
console.log(Mode([10,2,5, 4, 5, 2, 4])) //5

Advertisement

Answer

If you only need the first one that its repeated you can try this approach

  const checkMode = (array = []) => {

    const duplicated = array.find(value => array.filter(_value => value === _value).length > 1)

    return duplicated >= 0 ? duplicated: -1
  }

checkMode([10,2,5, 4, 5, 2, 4])

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement