Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
How to find the most occuring item in an array JS?

I have an array of objects which contain a "location" key. I already filtered and mapped the events array to a new visitedlocations array so that it only contains the locations. Now I can't figure out how to filter out the most occuring item in the visitedLocations array. Anyone have an idea?

How i filtered the events array:

 const visitedLocations = state.events
    .filter((event) => event.timeline.startDate < today)
    .map((event) => {
      return event.location;
    });
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

const arr = ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 1, 1, 2]
const unique = [...new Set(arr)] // Get unique values/keys
const counts = unique.map(key => (  // Make ojects with each key's count in original array
     {
       'key' : key,
       'count': arr.filter(element => element === key).length 
     } 
  ))
const sorted = counts.sort((a, b) => b.count - a.count) // Sort array based on counts
const mostOccurring = sorted[0] // Get first (largest) value

console.log('Unique: ', unique)
console.log('Counts: ', counts)
console.log('Sorted: ', sorted)
console.log('Most occuring: ', mostOccurring)

about 4 years ago · Santiago Trujillo Relatório

0

You can achieve that by using Array.reduce().

Live Demo :

const data = ['location 1', 'location 1', 'location 1', 'location 1', 'location 1', 'location 3', 'location 5', 'location 5'];

function freq(locationArr) {
  return locationArr.reduce((acc, curr) => {
    acc[curr] = -~acc[curr];
    return acc;
  }, {});
}

// Convert object into a 2D array.
const arr = Object.entries(freq(data));

// Now sorting the array based on the first index values. 
const sortedResult = arr.sort((a, b) => b[1] - a[1]);

console.log(sortedResult[0]);

about 4 years ago · Santiago Trujillo Relatório

0

Considering the answer given by Matthew Flaschen here.

No need to use map, sort, reduce or filter functions.

It could be achieved using single for loop and couple of if...else statements.

Below given approach should be O(n).

function mostFrequentLocations(array)
{
    if(!array.length) return null;

    let modeMap = {};
    let maxEl = array[0];
    let maxCount = 1;

    for(let i = 0; i < array.length; i++)
    {
        let el = array[i];

        if(modeMap[el] === null) modeMap[el] = 1;

        else modeMap[el]++;
  
        if(modeMap[el] > maxCount)
        {
            maxEl = el;
            maxCount = modeMap[el];
        }
    }

    return maxEl;
}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda