// reduce实现数组去重
let a =[1,1,11,2,3,4,3]
let obj= a.reduce((pre,cur)=>{
if(!pre.includes(cur)){
return pre.concat(cur)
}else{
return pre
}
},[])
console.log(obj);
// reduce实现统计出现次数
let b=['a','a','b','c','c','c','c']
let obj2=b.reduce((pre,cur)=>{
if(cur in pre){
pre[cur]++
}else{
pre[cur]=1
}
return pre
},{})
console.log(obj2);
// 对象去重
function arr(aa){
let obj={};
for(let i=0;i<aa.length;i++){
obj[aa[i]]=aa[i]
}
return Object.values(obj)
}
console.log(arr(b));
// 利用reduce实现二维数组转换成一维数组
let arr1=[[1,2],[3,4],[4,5]]
const myArr=arr1.reduce((pre,cur)=>{
return pre.concat(cur)
},[])
console.log(myArr);
// 将多维数组转换成一维数组
let arr2=[1,[1,[2,4,6,4]],[2,3]]
const newArr=function(arr){
return arr.reduce((pre,cur)=>{
return pre.concat(Array.isArray(cur)?newArr(cur):cur)
},[])
}
console.log(newArr(arr2));