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

158
Vistas
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 Respuestas
Responde la pregunta

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