JavaScript 2022

Term 3 Wednesday

May - July 2022

This site will be updated live during the sessions

Week 3 (e) Array Reduce Method

		
001let prices = [1.99, 0.55, .99, 99, 0.79];
		
002
		
003
		
004
		
005let totalAtStartOfTransaction = 0; //credit
		
006
		
007let total = prices.reduce(
		
008  (previousValue, currentValue) => 
		
009		previousValue + currentValue, totalAtStartOfTransaction
		
010);
		
011
		
012// previous value is the running total, 
		
013// current value is the value in the array element.
		
014// note, if an inital value is provided (the varible totalAtStartOfTransaction),
		
015// this will be stored as the initial previousValue 
		
016// and the 1st element looked at (as currentValue) will be at index 0
		
017// if no 3rd arguement, the value at index 0 is the initial
		
018// previousValue, and the first currentValue will be at index 1
		
019
		
020
		
021// toFixed(2) method displays value in total to 2 decimal places
		
022// but does not change the actual value stored
		
023console.log(total.toFixed(2));  //103.25
		
024console.log(total); //103.255465872147
		
025
		
026
		
027
		
028prices = [1.99, 0.55, .99, 99, 0.79];
		
029
		
030
		
031
		
032total = prices.reduce(
		
033  (previousValue, currentValue) => 
		
034		previousValue + currentValue
		
035);
		
036
		
037// toFixed(2) method displays value in total to 2 decimal places
		
038// but does not change the actual value stored
		
039console.log(total.toFixed(2)); 
		
040console.log(total);