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);
};
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);