使用 JavaScript 獲取陣列中第三小的數字
問題
我們需要寫一個 JavaScript 函式,它接收一個長度至少為 3 的數字陣列。
我們的函式應該從陣列中返回第三小的數字。
示例
以下是程式碼 −
const arr = [6, 7, 3, 8, 2, 9, 4, 5]; const thirdSmallest = () => { const copy = arr.slice(); for(let i = 0; i < 2; i++){ const minIndex = copy.indexOf(Math.min(...copy)); copy.splice(minIndex, 1); }; return Math.min(...copy); }; console.log(thirdSmallest(arr));
輸出
4
廣告