largestN
by Artem
JavaScript
'use strict';
const largestN = (inputArray, n) => {
const max = Math.max.apply(null, inputArray);
if (n === 1) {
return max;
}
if (inputArray.length === n) {
return Math.min.apply(null, inputArray);
}
const maxIndex = inputArray.findIndex(el => Object.is(el, max));
const newArray = inputArray.slice();
newArray.splice(maxIndex, 1)
return largestN(newArray, n - 1);
};
console.log(largestN([2, 4, 1, 5, 3], 1)); // 5
console.log(largestN([2, 4, 1, 5, 3], 2)); // 4
console.log(largestN([1, 8, 3, 2], 4)); // 1