数组中reduce的使用方法

向右看齐 2022-11-30 04:12 317阅读 0赞

1.出现元素的次数:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title></title>
  5. </head>
  6. <body>
  7. </body>
  8. </html>
  9. <script type="text/javascript">
  10. //出现元素的次数
  11. function arrCount(arr,val){
  12. let count=arr.reduce((pre,cur,index)=>{
  13. console.log(pre,cur);
  14. return pre+=cur==val?1:0
  15. },0)
  16. return count
  17. }
  18. console.log(arrCount([1,5,3,4,8,1,1],1));//3
  19. </script>

2.求数组最大值:

  1. //求最大值
  2. function arrCount(arr){
  3. let count=arr.reduce((pre,cur,index)=>{
  4. console.log(pre,cur);
  5. return pre>cur?pre:cur
  6. })
  7. return count
  8. }
  9. console.log(arrCount([1,5,3,4,8,1,1]));

3.数组去重使用reduce

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title></title>
  5. </head>
  6. <body>
  7. </body>
  8. </html>
  9. <script type="text/javascript">
  10. let goods=[
  11. {name:'apple',price:2000},
  12. {name:'huawei',price:1321},
  13. {name:'huawei',price:1421},
  14. {name:'huawei',price:13221},
  15. {name:'mi',price:20000},
  16. {name:'mi',price:20000},
  17. ]
  18. //数组去重
  19. function filterGoods(arr){
  20. return arr.reduce((pre,cur)=>{
  21. //去找数组中是否有重复的数据有就返回true
  22. let bool=pre.find((val)=>{
  23. return val.name==cur.name
  24. })
  25. //没有这个值就追加进去
  26. if(!bool){
  27. pre.push(cur)
  28. }
  29. return pre
  30. },[])
  31. }
  32. console.log(filterGoods(goods))
  33. </script>

发表评论

表情:
评论列表 (有 0 条评论,317人围观)

还没有评论,来说两句吧...

相关阅读