移除JavaScript陣列中任何數字/元素的奇數次出現
假設我們有一個這樣的數字陣列:
const arr = [1, 6, 3, 1, 3, 1, 6, 3];
我們需要編寫一個JavaScript函式,它只接收一個這樣的陣列作為引數。然後,函式應該查詢陣列中出現奇數次(不包括只出現一次)的所有數字。
例如:
在上面的陣列中,數字1和3都出現了3次(奇數),因此我們的函式應該刪除這兩個數字的第三次出現。
輸出陣列應該如下所示:
const output = [1, 6, 3, 1, 3, 6];
我們將準備一個雜湊表來跟蹤每個數字出現的次數,最後我們將遍歷該表以刪除出現奇數次的數字的最後一次出現。
我們對映中的每個鍵都將儲存一個數組值,該陣列的第一個元素將是該元素出現的次數,第二個元素將是它最後出現時的索引。
示例
程式碼如下:
const arr = [1, 6, 3, 1, 3, 1, 6, 3];
const removeOddOccurence = (arr =[]) => {
// keeping the original array unaltered
const copy = arr.slice();
const map = {};
arr.forEach((num, ind) => {
if(map.hasOwnProperty(num)){
map[num][0]++;
map[num][1] = ind;
}else{
map[num] = [1, ind];
};
});
for(const key in map){
const [freq, index] = map[key];
if(freq !== 1 && freq % 2 === 1){
copy.splice(index, 1, '');
};
};
return copy.filter(el => el !== '');
};
console.log(removeOddOccurence(arr));輸出
控制檯輸出將為:
[1, 6, 3, 1, 3, 6]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP