一道数组题,�把arr = [{type:1},{type:2},{type:1},{type:2},{type:3},{type:4}]
变成arrNew = [[{type:1},{type:1}],[{type:2},{type:2}],[{type:3}],[{type:4}]]
let arr = [{type:1},{type:2},{type:1},{type:2},{type:3},{type:4}];
let arrNew = []; //返回的新数组
let set = new Set(); //存放没重复的数组
//�第一种方式:使用forEach遍历
arr.forEach(element => {
if(!set.has(element.type)) { //如果有相同的type值,就不走一下判断
set.add(element.type);//向set追加type值,以标志下次判断
let arr1 = arr.filter(v => v.type===element.type);//过滤出元素type相等的数组
arrNew.push(arr1);//追加到新的数组中
}
});
//第二种方式�:使用map
arr.map(v => v.type) //返回只有type的数组
.forEach(type => { //遍历,下面方式跟上面思想一致
if(!set.has(type)) {
set.add(type);
let arr1 = arr.filter(v => v.type===type);
arrNew.push(arr1);
}
})
//重新排序,按type小到大。
arrNew.sort((a, b) => {
const x = a[0].type;
const y = b[0].type;
return x-y;
})