5 回答
TA贡献1811条经验 获得超5个赞
您可以采用一个对象对相同的值进行分组。
var array = [3, 2, 6, 2, 1, 3],
result = [],
group = {};
for (let value of array) {
if (!group[value]) result.push(group[value] = []);
group[value].push(value);
}
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
TA贡献2037条经验 获得超6个赞
我相信它可以写得更短,更简单,这是我的镜头:
function group(arr) {
let dubArray = []
arr.forEach((item) => {
let itemArr = []
arr = arr.filter((repeatItem)=>{
if(item === repeatItem) {
itemArr.push(item)
return false
}
return true
})
if(itemArr.length > 0 )
dubArray.push(itemArr)
})
return dubArray
}
console.log(group([1, 2, 1, 5, 5, 1]))
TA贡献1816条经验 获得超4个赞
Map 对象在此类情况下非常有用。它非常有效,并且迭代条目始终按插入顺序进行。
let arr = [3, 2, 6, 2, 1, 3];
// form a Map with number as key sub arrays as value
let aMap = new Map();
arr.forEach(num => {
if (!aMap.has(num)) { aMap.set(num, []); }
let subArr = aMap.get(num);
subArr.push(num);
aMap.set(num, subArr);
});
// loop through Map to form array of sub-arrays
let counts = [];
aMap.forEach(subArr => {
counts.push(subArr);
});
const result = document.getElementById('result');
result.innerHTML = 'arr: ' + JSON.stringify(arr) + '\n';
result.innerHTML += 'aMap: {';
aMap.forEach((subArr, number) => {
result.innerHTML += ` ${number} => ${JSON.stringify(subArr)},`;
});
result.innerHTML += ` }\n`;
result.innerHTML += 'counts: ' + JSON.stringify(counts);
<pre id="result"></pre>
TA贡献1890条经验 获得超9个赞
我做了一个函数,可以做到这一点,称为组。
let test = [3, 2, 6, 2, 1, 3];
function group(list){
let result = [];
let used = []
for (let i = 0; i<list.length; i++){
let sames = [];
for (let j = i+1; j<list.length; j++){
if (list[i] == list[j] && !used.includes(list[i])){
sames.push(list[j])
}
}
if (!used.includes(list[i])){
sames.push(list[i])
}
used.push(list[i]);
if (sames.length > 0){
result.push(sames)
}
}
return result
}
console.log(group(test))
TA贡献1797条经验 获得超6个赞
let arr = [3, 2, 6, 2, 1, 3];
let unique_set = []; // storage of first occured unique numbers
let result = [];
arr.forEach(n => {
let index = unique_set.indexOf(n);
if( index !== -1 ) return result[index].push(n);
unique_set.push(n);
result.push( [n] );
// the index of number in set, and index of result array will always match
});
console.log(result);
添加回答
举报