如何把[1,1,1,2,2,2,3,3,3] 变成[[1,1,1],[2,2,2],[3,3,3]]
方法1
var arr = [1,1,1,2,2,2,3,3,3];
var temp = new Array;
var result = new Array;
temp.push(arr[0]);
for (var i = 1; i<arr.length; i++) {
var flag = 0;
for(var j = 0; j<temp.length; j++){
if (arr[i] == temp[j]) {
flag = 1;
break;
}
}
if (flag == 0) {
temp.push(arr[i]);
}
}
for (var i = 0; i<temp.length; i++){
var array1 = new Array;
var count = 0;
for(var j = 0; j<arr.length; j++){
if (arr[j] == temp[i]) {
array1.push(arr[j]);
count++;
}
}
if (count>1) {
result.push(array1);}
else{
result.push(temp[i]);
}
}
console.log("result",result);
方法2
let arr = [1,1,1,2,2,2,3,3,3],
arr2 = [],
obj = {},
index = 0;
arr.map(function (item) {
if(obj[item] === undefined){
obj[item] = index++;
arr2.push([item]);
}else{
arr2[obj[item]].push(item)
}
})
console.log(arr2)
方法3
arr.map( (item) => {
if (!!obj[item]) {
// 如果已存在,直接存入
arr2[obj[item]].push(item)
} else {
// 如果不存在,在索引对象中创建索引,根据索引创建数组
obj[item] = arr2.length
arr2[obj[item]] = [item]
}
})
方法4
arr.map( item => obj[item] ? arr2[obj[item]].push(item) : arr2[obj[item] = arr2.length] = [item])
网友评论