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

215
Vistas
Finding the mode of each column in a two-dimensional array - JavaScript

Not a question, just putting this out there if someone would need it. (caused me a lot of headache)

The script below can take a 2d array of any number number of 2nd-layer arrays as 'myArray' and create a single array of the most frequent element (regardless of type) in each column of the original 2d array.

myArray = myArray[0]
  .map((_, col) => myArray.map((row) => row[col]))
  .map((array) =>
    array.reduce(
      (a, b, i, arr) =>
        arr.filter((v) => v === a).length >= arr.filter((v) => v === b).length
          ? a
          : b,
      null
    )
  );
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

What it does: The code below will take any two-dimensional array “myArray” and return a one-dimensional array with the mode of each column of the original 2-d array.

How it works: The input (2-d array) is transposed and the resulting array is searched for the most common element in each row. It is then reduced to then flattened (reduced) and re-transposed to a 1d array containing the most common elements of each column of the original array.

myArray = [
  [1, 2, 3, 4, 5],
  [1, 2, 3, 4, 7],
  [1, 3, 3, 6, 7],
  [1, 5, 3, 4, 7],
  [1, 6, 3, 4, 7],
  [1, 7, 3, 8, 5],
];

myArray = myArray[0]
  .map((_, col) => myArray.map((row) => row[col]))
  .map((array) =>
    array.reduce(
      (a, b, i, arr) =>
      arr.filter((v) => v === a).length >= arr.filter((v) => v === b).length ?
      a :
      b,
      null
    )
  );

console.log(myArray);

about 4 years ago · Juan Pablo Isaza 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