Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!