在 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 ] ]
广告