find the average of a list of numbers in javascript

To find the average of a list of numbers in JavaScript, you can use the reduce() method to sum up all the numbers in the list and then divide by the length of the list. Here's an example code snippet:

index.tsx
const numbers = [5, 10, 15, 20, 25];

const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
});

const avg = sum / numbers.length;

console.log(avg); // Output: 15
207 chars
10 lines

In this code, the reduce() method iterates over the array and adds each number to an accumulator variable which starts at 0. The final sum is divided by the length of the array to get the average. The result is then logged to the console.

gistlibby LogSnag