Advertisement
rbcorrea

Array reducer

Mar 25th, 2023 (edited)
598
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // If you're using an array of objects you should use this one.
  2. let arrayOfObjects = [
  3.     { name: "paper", quantity: 100, unitPrice: 1.96 },
  4.     { name: "pen", quantity: 57, unitPrice: 1.22 },
  5.     { name: "eraser", quantity: 6, unitPrice: .35 }
  6. ]
  7.  
  8. let totalObjectsPrice = arrayOfObjects.reduce((acc, { quantity, unitPrice }) => {
  9.   return acc + Math.round(quantity * unitPrice);
  10. }, 0);
  11.  
  12. // If you're using an array of integers you should use this one.
  13. let arrayOfNumbers = [196, 69.53, 2.09];
  14.  
  15. let totalNumbersPrice = arrayOfNumbers.reduce((prev, next) => Math.round(prev + next));
  16.  
  17. console.log(["array of objects price: ", totalObjectsPrice, " array of numbers price: ", totalNumbersPrice])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement