在 JavaScript 中獲取陣列中的最大 n 個值
我們需要編寫一個 JavaScript 函式,該函式將數字陣列作為第一個引數,將一個數字(假設為 n)作為第二個引數。
然後,我們的函式應該從陣列中選取 n 個最大的數字,並返回包含這些數字的新陣列。
示例
程式碼實現如下 −
const arr = [3, 4, 12, 1, 0, 5, 22, 20, 18, 30, 52]; const pickGreatest = (arr = [], num = 1) => { if(num > arr.length){ return []; }; const sorter = (a, b) => b - a; const descendingCopy = arr.slice().sort(sorter); return descendingCopy.splice(0, num); }; console.log(pickGreatest(arr, 3)); console.log(pickGreatest(arr, 4)); console.log(pickGreatest(arr, 5));
輸出
控制檯中輸出如下 −
[ 52, 30, 22 ] [ 52, 30, 22, 20 ] [ 52, 30, 22, 20, 18 ]
廣告