|
| 1 | +/* |
| 2 | +Let’s consider a list of prices in a bill: |
| 3 | +4.6, 5.03, 7.99, 8.01 |
| 4 | +instead of writing the like below |
| 5 | +const price0 = 4.6; |
| 6 | +const price1 = 5.03; |
| 7 | +const price2 = 7.99; |
| 8 | +const price3 = 8.01; |
| 9 | +We can write it as an array literal |
| 10 | +const items = [4.6, 5.03, 7.99, 8.01]; |
| 11 | +
|
| 12 | +The Array object, as with arrays in other programming languages, enables storing a collection |
| 13 | +of multiple items under a single variable name, and has members for performing common array operations. |
| 14 | +Arrays can store items of any type & multiple pieces of information. |
| 15 | +
|
| 16 | +In JavaScript, we can use [] notation to access specific elements in the array using index numbers. |
| 17 | +The index numbers start from 0. |
| 18 | +
|
| 19 | +
|
| 20 | +const items = [4.6, 5.03, 7.99, 8.01]; |
| 21 | +console.log(items[0]); // 4.6 |
| 22 | +console.log(items[1]); // 5.03 |
| 23 | +console.log(items[2]); // 7.99 |
| 24 | +console.log(items[3]); // 8.01 |
| 25 | +// Accessing elements using index numbers |
| 26 | +*/ |
| 27 | +const items = [4.6, 5.03, 7.99, 8.01]; |
| 28 | +function calculateMean(list) { |
| 29 | + // Calculate the sum of all elements in the array |
| 30 | + const sum = list.reduce( |
| 31 | + (accumulator, currentValue) => accumulator + currentValue, |
| 32 | + 0 |
| 33 | + ); |
| 34 | + // Calculate the mean by dividing the sum by the number of elements |
| 35 | + const mean = sum / list.length; |
| 36 | + return mean; |
| 37 | +} |
0 commit comments