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

219
Visualizações
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 Respostas
Responde à pergunta

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 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