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

95
Visualizações
How can I find the two positions with the two highest numbers in a multidimensional array?

I'm working in a JavaScript project where in this case I am trying to get the two arrays with the biggest value in position 2.

[-20.172, 35.251, 0],
[-16.368, 21.792, 26.81],
[-29.311, 18.393, 0],
[14.54, 15.23, 0],
[-1.61, 12.91, 27.692],
[0, 0, 0]

the intended answer should be like this:

[-16.368, 21.792, 26.81],
[-1.61, 12.91, 27.692]

I can't sort by the ones that have a zero and the ones who doesn't have it, some other cases in the project I'm working could possibly have different numbers on the position 2.

any suggestions?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I can't sort by the ones that have a zero

Could it be the array is declared const?


Array.Sort

Array.Slice

  • sorts, in place, descending
  • returns an array of (copies of) first 2 elements

    var topTwo = function ( array_of_arrays ) {
      return array_of_arrays.sort((a, b) => b[2] - a[2])
                            .slice(0, 2) ;
    };

    var arr = [
      [-20.172, 35.251, 7],
      [-16.368, 21.792, 26.81],
      [-29.311, 18.393, 0],
      [14.54, 15.23, 0],
      [-1.61, 12.91, 27.692],
      [0, 0, -3]
    ];
    console.log( topTwo(arr) );
    

about 4 years ago · Juan Pablo Isaza Relatório

0

Using Array#reduce:

const arr = [
  [-20.172, 35.251, 0],
  [-16.368, 21.792, 26.81],
  [-29.311, 18.393, 0],
  [14.54, 15.23, 0],
  [-1.61, 12.91, 27.692],
  [0, 0, 0]
];

const [max1Index, max2Index] = arr.reduce(([max1Index, max2Index], { 2: num }, index) => {
  const max1 = arr[max1Index][2], max2 = arr[max2Index][2];
  return num > max1
    ? [index, max1Index]
    : num > max2
      ? [max1Index, index]
      : [max1Index, max2Index];
}, [0, 0]);

console.log(arr[max1Index], arr[max2Index]);

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