# 前端-reduce

1.返回指定键值对
function getkeys(obj={},keys=[]){

``return Object.keys(obj).reduce((t,v)=>(keys.includes(v)&& (t[v] = obj[v]),t),{})``

}
==>
function getkeys(obj={},keys=[]){

`````` return Object.keys(obj).reduce((t,v)=>{
if(keys.includes(v)){
t[v]=obj[v]
}
return t;
},{})``````

}
const target = {a:1,b:2,c:3};
const keyword = ["a","b"];
console.log(getkeys(target,keyword)); //{a:1,b:2}

2.累加累乘
function Accu(...vals){

``return vals.reduce((t,v)=>t + v,0)``

}
function Mccu(...vals){

``return vals.reduce((t,v)=>t * v,1)``

}

const a = Accu(1,2,3,4,5); //15
const b = Mccu(1,2,3,4,5); //120

3.权重求和
const scores = [

``````{score:90,name:"语文",weight:0.5},
{score:95,name:"数学",weight:0.3}``````

];
const result = scores.reduce((t,v)=>{

``return t + v.score * v.weight``

},0);
console.log(result); //90.5

4.数组扁平化
function flat(arr = []){

``return arr.reduce((t,v)=>t.connat(Array.isArray(v)?flat(v):v),[])``

};
const arr = [0,1,[2,3],4,[5,[6,7]]];
console.log(flat(arr)); //[0,1,2,3,4,5,6,7]

5.数组成员个数统计
function count(arr=[]){

``return arr.reduce((t,v)=>(t[v]=(t[v]||0)+1,t),{})``

};
const arr = [0,1,1,2,2,2];
console.log(count(arr)); //{0:1,1:2,2:3}

6.记录元素出现的位置
function position(arr=[],val){

``return arr.reduce((t,v,i)=>(v===val && t.push(i),t),[])``

}

const arr = [2,1,5,4,2,1,6,6,7,2];
console.log(position(arr,2)); //0

7.去重
let arr = [

``````{id:1,name:"绝技"}
{id:2,name:"绝技1"}
{id:1,name:"绝技"}``````

]
function unique(uniqueArr,arr){

``````let obj = {};
return uniqueArr.reduce((t,v)=>(!obj[v[key]] &&             (obj[v[key]] = true && t.push(v)),t),[]);``````

},
console.log(unique(arr),id);

8.过滤数组
const arr1 = [1,2,3,4,5,6];
const arr2 = [2,3,5];
function diff(arr=[],oarr=[]){

``return arr.reduce((t,v)=>(!oarr.includes(v) &&             t.push(v),t),[])``

}

==>

function diff(arr=[],oarr=[]){

``````return arr.reduce((t,v)=>{
if(!oarr.includes(v)){
t.push(v)
}
return t;
},[])``````

}
console.log(diff(arr1,arr2)); //[1,4,6]

0 声望
0 粉丝
0 条评论