数组reduce方法
2020-03-16 本文已影响0人
小雪洁
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>数组reduce方法</title>
</head>
<body>
</body>
<script>
let a=[1,2,3,4,5];
//arr.reduce(function(pre,item,index,arr){},a)对于统计数组数据非常好用
//其中pre代表上次的返回值,item代表本次循环的元素值,a是初次循环时pre的值
a.reduce(function(pre,item,index,arr){
//console.log(pre,item);
return 10;
},0);
//使用arr.reduce()找出数组中最大值
let b=[1,5,89,2];
let max=b.reduce(function(pre,item,index,arr){
return item>pre?item:pre;
});
console.log(max);//89
//使用arr.reduce()找出数组中最小值
let min=b.reduce(function(pre,item,index,arr){
return item<pre?item:pre;
});
console.log(min); //1
//统计数组中出现2的次数
let c=[1,2,3,4,5,2,6,2];
//方法1
let count0=0
for(const v of c){
v==2?count0++:""
}
console.log(count0);//3
//方法2
let count=c.reduce(function(pre,item){
item==2?pre++:"";
return pre;
},0);
console.log(count);//3
let goods=[
{name:"apple",price:10},
{name:"banana",price:30},
{name:"grape",price:20}
];
//筛选价格最贵的商品
function maxPrice(goods){
return goods.reduce(function(pre,item,index,arr){
return pre.price>item.price?pre:item;
});
}
console.log(maxPrice(goods));
//商品价格求和
function sum(goods){
return goods.reduce(function(total,item,index,arr){
total+=item.price;
return total;
},0);
}
console.log(sum(goods));//60
//输出价格超过20的商品名称
function getNameByPrice(goods,price){
return goods.reduce(function(pre,item){
item.price>price?pre.push(item.name):"";
return pre;
},[]);
}
console.log(getNameByPrice(goods,10));//["banana", "grape"]
//数组去重
let e=[1,2,3,4,5,2,6,2];
let ee= e.reduce(function(pre,item,arr){
pre.includes(item)?pre:pre.push(item);
return pre;
},[]);
console.log(ee);
let f= e.reduce(function(pre,item,arr){
//console.log(pre)
if(pre.includes(item)==false){
pre.push(item);
}
return pre;
},[]);
console.log(e);//原数组不变
console.log(f);// [1, 2, 3, 4, 5, 6]
//商品去重
let goods0=[
{name:"apple",price:10},
{name:"banana",price:30},
{name:"grape",price:20},
{name:"apple",price:10},
{name:"banana",price:30},
{name:"grape",price:20}
];
function goodsFilter(goods){
return goods.reduce(function(arr,cur){
let find=arr.find(function(item,index){
return item.name==cur.name;
});
if(!find){
arr.push(cur);
}
return arr;
},[])
}
console.log(goods0);
console.log(goodsFilter(goods0));
</script>
</html>