將相同條目分組到子陣列中 - JavaScript
比如說,我們有一個數字陣列,其中包含有相同的條目。我們需要寫一個函式來接受此陣列,將所有相同的條目分組到一個子陣列中,並返回以這種方式形成的新陣列。
例如:如果輸入陣列是 -
const arr = [234, 65, 65, 2, 2, 234];
則輸出應為 -
const output = [[234, 234], [65, 65], [2, 2]];
我們將使用一個散列表來跟蹤已經出現的元素,並使用 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 ] ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP