1.出现元素的次数:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
<script type="text/javascript">
//出现元素的次数
function arrCount(arr,val){
let count=arr.reduce((pre,cur,index)=>{
console.log(pre,cur);
return pre+=cur==val?1:0
},0)
return count
}
console.log(arrCount([1,5,3,4,8,1,1],1));//3
</script>
2.求数组最大值:
//求最大值
function arrCount(arr){
let count=arr.reduce((pre,cur,index)=>{
console.log(pre,cur);
return pre>cur?pre:cur
})
return count
}
console.log(arrCount([1,5,3,4,8,1,1]));
3.数组去重使用reduce
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
<script type="text/javascript">
let goods=[
{name:'apple',price:2000},
{name:'huawei',price:1321},
{name:'huawei',price:1421},
{name:'huawei',price:13221},
{name:'mi',price:20000},
{name:'mi',price:20000},
]
//数组去重
function filterGoods(arr){
return arr.reduce((pre,cur)=>{
//去找数组中是否有重复的数据有就返回true
let bool=pre.find((val)=>{
return val.name==cur.name
})
//没有这个值就追加进去
if(!bool){
pre.push(cur)
}
return pre
},[])
}
console.log(filterGoods(goods))
</script>
还没有评论,来说两句吧...