在 JavaScript 中合併相同的項
我們有一個包含相同條目的陣列。我們需要編寫一個函式來接收該陣列,並將所有相同條目分組到一個數組中,並返回從而形成的新陣列。
例如:如果輸入陣列為 −
const arr = [234, 65, 65, 2, 2, 234];
// 則輸出應為 −
const output = [[234, 234], [65, 65], [2, 2]];
我們將使用一個 HashMap 來追蹤已經出現的元素,並使用一個 for 迴圈來遍歷陣列。
因此,讓我們為這個函式編寫程式碼 −
示例
程式碼如下 −
const arr = [234, 65, 65, 2, 2, 234]; 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));
輸出
控制檯中的輸出將是 −
[ [ 234, 234 ], [ 65, 65 ], [ 2, 2 ] ]
廣告