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

156
Visualizações
Return Two Highest Values in List, in Javascript

I can't figure this one out, I wrote a messy code for it, and now I am don't know how to fix it or what to do next.

In this kata, your job is to return the two distinct highest values in a list. If there're less than 2 unique values, return as many of them, as possible. The result should also be ordered from highest to lowest.

Example

[4, 10, 10, 9]  =>  [10, 9]
[1, 1, 1]  =>  [1]
[]  =>  []

Source https://www.codewars.com/kata/57ab3c09bb994429df000a4a/train/javascript

This is my incorrect code

function twoHighest (arr) {
let max1 = Math.max(...arr);
  
var i = 0;
  while (i < arr.length) {
    if (arr[i] === max1) {
      arr.splice(i, 1);
    } else {
      ++i;
    }
  }
  var array2 = arr;
  var maxone = [max1];
  let max2 = [Math.max(...array2)];
  return maxone.concat(max2);
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Step 1: Unique array by Array.filter

Step 2: Sort by DESC by Array.sort

Step 3: Get first 2 element of sorted array by Array.slice

function twoHighest(arr) {
  return arr
    .filter((v, i, a) => a.indexOf(v) === i)  // Unique array
    .sort((a, b) => b - a)  // Sort by DESC
    .slice(0, 2);  // Get first 2 element of sorted array
};

const demoArray = [15, 20, 20, 17];
const result = twoHighest(demoArray);
console.log(result);

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