Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
¿Cómo encontrar el elemento más recurrente en una matriz JS?

Tengo una serie de objetos que contienen una clave de "ubicación". Ya filtré y asigné la matriz de eventos a una nueva matriz de ubicaciones visitadas para que solo contenga las ubicaciones. Ahora no puedo averiguar cómo filtrar el elemento más frecuente en la matriz de ubicaciones visitadas. ¿Alguien tiene una idea?

Cómo filtré la matriz de eventos:

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

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 Report

0

Puede lograrlo usando Array.reduce() .

Demostración en vivo :

 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 Report

0

Teniendo en cuenta la respuesta dada por Matthew Flaschen aquí .

No es necesario utilizar las funciones map , sort , reduce o filter .

Se podría lograr usando un solo bucle for y un par de sentencias if...else .

A continuación, el enfoque dado debe ser 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!