Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

224
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda