将相同条目分组到子数组中 - 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