Advertisement
ivana_andreevska

Reduce Method for Arrays

Dec 22nd, 2021
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const items=[
  2.    { name:'Bike' , price:100} ,
  3.    { name:'TV' , price:200} ,
  4.    { name:'Album' , price:10} ,
  5.    { name:'Book' , price:5} ,
  6.    { name:'Phone' , price:500} ,
  7.    { name:'Computer' , price:1000} ,
  8.    { name:'Keyboard' , price:25}
  9.  
  10. ]
  11.  
  12. const total=items.reduce((currentTotal , item)=>{
  13.     //it takes an item and a property we want to reduce to
  14.     //a second parameter is a starting point in this case 0
  15.  
  16.     return item.price + currentTotal;
  17.  
  18. },0)
  19. console.log(total);
  20. //reduce method runs a function on every membr of the array
  21. //the first member of that function(currentTotal) is going to be whatever the previous iteration of this array returned
  22. //the second item(item) is the actual item in the array
  23. //the currentTotal is going to start on the very first iteration with whatever we pass in as a second parametar(this case 0)
  24.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement