在javascript中为重复元素创建新数组 [英] create new arrays for repeating elements in javascript
本文介绍了在javascript中为重复元素创建新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含8个元素的JavaScript数组,有些元素在重复。我想为相同的元素创建单独的数组。
I have a JavaScript array with 8 elements and some elements are repeating. I want to create separate arrays for identical elements.
示例:
原始数组是[1,1,1,3, 3,1,2,2]
结果数组将是[1,1,1,1],[3,3],[2,2]
example: original array is [1,1,1,3,3,1,2,2] resulting arrays will be [1,1,1,1],[3,3],[2,2]
我想要一个与此类似的函数:
I want a function similar to this:
var array=[1,1,1,3,3,1,2,2];
var createNewArrays=function(array){
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array.length; j++) {
}
}
};
推荐答案
您可以使用哈希表作为集合子数组的引用。
You could use a hash table as reference to the sub arrays for the collection.
var array = [1, 1, 1, 3, 3, 1, 2, 2],
result = [];
array.forEach(function (a) {
a in this || result.push(this[a] = []);
this[a].push(a);
}, Object.create(null));
console.log(result);
这篇关于在javascript中为重复元素创建新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文