在 JavaScript 中從陣列中查詢匹配對
我們需要編寫一個 JavaScript 函式,該函式採用一個可能包含一些重複值的整陣列成的陣列。我們的函式應找出我們可以從陣列中提取出的相同整數對的數量。
例如 -
如果輸入陣列為 -
const arr = [1, 5, 2, 1, 6, 2, 2, 9];
那麼輸出應該為 -
const output = 2;
因為所需的配對是 1,1 和 2,2
示例
其程式碼為 -
const arr = [1, 5, 2, 1, 6, 2, 2, 9]; const countPairs = (arr = []) => { const { length } = arr; let count = 0; // making a shallow copy so that the original array remains unaltered const copy = arr.slice(); copy.sort((a, b) => a - b); for(let i = 0; i < length; i++){ if(copy[i] === copy[i + 1]){ i++; count++; }; }; return count; }; console.log(countPairs(arr));
輸出
控制檯中的輸出將為 -
2
廣告