檢查陣列的某些元素是否相同 JavaScript
我們有一個包含一些冗餘專案的陣列,我們的工作是編寫一個函式,該函式接受該陣列並將所有相同的專案組合到一個子陣列中,並返回由此形成的新陣列。
例如 −
//If the input array is: const arr = [1, 3, 3, 1]; //then the output should be: const output = [[1, 1], [3, 3]];
我們將使用 HashMap 來跟蹤已經發生的元素,並使用 for 迴圈迭代陣列,程式碼如下 −
示例
const arr = [1, 3, 3, 1]; const groupArray = arr => { const map = {}; const group = []; for(let i = 0; i < arr.length; i++){ if(typeof map[arr[i]] === 'number'){ group[map[arr[i]]].push(arr[i]); } else { //the push method returns the new length of array //and the index of newly pushed element is length-1 map[arr[i]] = group.push([arr[i]])-1; } }; return group; } console.log(groupArray(arr));
輸出
控制檯中的輸出將是 −
[ [ 1, 1 ], [ 3, 3 ] ]
廣告