Среднее значение массива чисел javascript

Average or Arithmetic mean of an array using Javascript

The goal of this article is to calculate the average of an array using JavaScript. Before we do that, let’s quickly understand what the terms ‘Average’ & ‘Array’ mean.

Average or Arithmetic mean is a representation of a set of numbers by a single number. Its value can be obtained by calculating the sum of all the values in a set and dividing the sum by the number of values.

Consider the following set of numbers: 1, 2, 3 & 4

An array is a container object that holds a fixed number of values of a single type. An array’s length, once created, would remain constant/fixed.

You can go through other basic concepts of object-oriented programming such as looping, conditional statements, user-defined functions, and classes to understand this blog better.

Table of Contents

Explanation

Simple approach to finding the average of an array

We would first count the total number of elements in an array followed by calculating the sum of these elements and then dividing the obtained sum by the total number of values to get the Average / Arithmetic mean.

Breaking down the array average algorithm

Mean of an array can be obtained in 3 steps:

Step 1: Finding the total number of elements in an array (basically, its length)

This can be obtained by calculating the length of the array using the length method.

Step 2: Finding the sum of all the elements of an array (sum)

We would need to traverse the array to find the sum. We initialize a variable called ‘total’ and loop over the array and add each element of the array to the ‘total’ variable

Step 3: Dividing the values obtained in Step 1 & 2.(sum/length)

Code — Getting average of an array using JavaScript

class Avg < constructor() <>static average(array) < var total = 0; var count = 0; jQuery.each(array, function(index, value) < total += value; count++; >); return total / count; > > var arry = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; console.log(Avg.average(arry)); 

Alternate Methods

Using Foreach loop

arry = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; function calculateAverage(array) < var total = 0; var count = 0; array.forEach(function(item, index) < total += item; count++; >); return total / count; > console.log(calculateAverage(arry)); 

Using jQuery

var arry = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; var total = 0; var count = 0; jQuery.each(arry, function(index, value) < total += value; count++; >); console.log(total / count); 

Using a function

var arry = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; function calculateAverageOfArray(array) < var total = 0; var count = 0; jQuery.each(arry, function(index, value) < total += value; count++; >); return total / count; > console.log(calculateAverageOfArray(arry)); 

Using a class

class Avg < constructor() <>static average(array) < var total = 0; var count = 0; jQuery.each(array, function(index, value) < total += value; count++; >); return total / count; > > var arry = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; console.log(Avg.average(arry)); 

Источник

Читайте также:  Cpython отличия от python

Как найти среднее арифметическое массива javascript

Хотел бы предложить вариант нахождения среднего арифметического массива с использованием цикла for :

const arr = [1, 3, 5, 7, 9, 11]; const getAverage = (numbers) =>  let sum = 0; // объявляем переменную, в которой будет храниться сумма всех чисел массива for (let i = 0; i  numbers.length; i += 1)  // инициализируем цикл sum += numbers[i]; // на каждой итерации прибавляем к сумме значение текущего элемента массива > return sum / numbers.length; // возвращаем среднее арифметическое >; console.log(getAverage(arr)); // => 6 

Inline версия первого варианта

 numbers.reduce((acc, number) => acc + number, 0) / numbers.length console.log(getAverage([1, 2, 3, 4])) // => 2.5 

Чтобы найти среднее арифметическое элементов массива, нужно сумму элементов массива разделить на длину массива. Для нахождения суммы элементов массива можно использовать функцию высшего порядка или цикл.

const getAverage = (numbers) =>  const sum = numbers.reduce((acc, number) => acc + number, 0); const length = numbers.length; return sum / length; >; const numbers = [1, 2, 3, 4]; console.log(getAverage(numbers)); // => 2.5 

Источник

JavaScript How to Calculate Average of an Array

However, if this does not ring any bells, I recommend reading further.

In this guide, you learn how to calculate the average of an array of numbers in three different ways:

  1. The for loop approach
  2. The forEach() function
  3. The reduce() function

Before jumping into these, let’s make sure you understand what it means to calculate the average in the first place.

Average in Mathematics

In mathematics, the average is the middle value of a group of numbers. The average is also commonly called the mean or the arithmetic mean.

The average is calculated by dividing the sum of all the values by the number of values.

Example. Find the average age of a group of students in this table:

Name Age
Alice 32
Bob 25
Charlie 23
David 24
Eric 26

Solution. Let’s sum up the ages and divide the result by the number of students:

s = 32 + 25 + 23 + 24 + 26 = 130 n = 5 avg = s / n = 130 / 5 = 26

Calculating the average is a useful way to describe data in statistics.

For instance, you can calculate the average of your grades to get an idea of how well your studies are going.

Anyway, let’s jump into the coding part of this tutorial.

Let’s implement a basic JavaScript for loop to find the average first.

Find the Average with For Loop in JavaScript

Perhaps the most beginner-friendly way to find the average of a JavaScript array is by using a for loop for summing up the numbers.

Here is how to use a for loop to find the average of an array of numbers:

  1. Create an array of numbers.
  2. Initialize the sum variable to accumulate the numbers.
  3. Loop through the numbers and add each number to the sum.
  4. Divide the sum of numbers by the number of numbers in the array.
  5. Show the result.
const arr = [1, 2, 3, 4, 5]; var sum = 0; for (var number of arr) < sum += number; >average = sum / arr.length; console.log(average);

Although there is nothing wrong with this approach, we can make it way shorter and more concise.

Next up, you are going to learn how to use the forEach() function for calculating the average.

The following examples are more intermediate. Do not worry if you find them a bit tricky as a beginner!

Find the Average Using forEach()

In JavaScript, there is a built-in function called forEach().

This function is used to run a give function for each element in the array.

In other words, the forEach() function behaves a lot like a for loop. It iterates through the array and calls the given function for each element.

To find the average using forEach() function:

  1. Create an array of numbers.
  2. Initialize the sum to 0.
  3. UseforEach() function to loop through the numbers and add each number to the sum.
  4. Divide the sum of numbers by the number of numbers in the array.
  5. Show the result.

To make the forEach() add each number to the sum, it needs to take a function that accepts a number argument and adds it to the sum.

const arr = [1, 2, 3, 4, 5]; var sum = 0; arr.forEach(function(num) < sum += num >); average = sum / arr.length; console.log(average);

To make it a bit more concise, you can also use the arrow function notation in the forEach() function call:

const arr = [1, 2, 3, 4, 5]; var sum = 0; arr.forEach((num) => < sum += num >); average = sum / arr.length; console.log(average);

Although this approach is a bit shorter than the for loop approach, it is still not the most elegant one.

Next, let’s use the reduce() function to find the average of an array of numbers.

This will make the process significantly more straightforward.

Find the Average Using reduce()

In JavaScript, there is a built-in function called reduce().

This function works the same way as folding in mathematics. Reducing means you fold a group of numbers into a single value.

For example, you can reduce or fold an array of numbers to get the sum of it.

The reduce() function takes a function as its argument. This is called a reducer.

It also takes an initial value for the accumulated result as its second argument.

Here is how the reduce() function and the reducer function operate on an array:

  1. Call a reducer on the first two elements of the array to get a partial result.
  2. Call the same function on the partial result and the third element of the array to create a new result.
  3. Repeat until there are no more values left.
  4. Return the result.

Now, let’s use the reduce() to find the average of a function.

const arr = [1, 2, 3, 4, 5]; const average = arr.reduce((a, b) => a + b, 0) / arr.length; console.log(average);

Let’s take a moment to understand how this piece of code works:

  1. The reducer (a, b) => a + b is called for each number in the array, where
    • a is the “result so far”.
    • b is the next number.
  2. The second argument of the reduce() function call is 0. This is the initial value for the sum of the array.
  3. The reduce() function is used to find the sum of the numbers in the array.
  4. The sum is then divided by the length of the array to get the average.

As you can see, this piece of code is way shorter than the for-loop approach. Once you learn how to read the reduce() function a bit better, you notice how much simpler this piece of code is than the lengthy for loop.

To find a complete guide on how to use the reduce() function in JavaScript, feel free to read this article.

This completes the example.

Now you should have a great understanding of how to calculate the average of an array in JavaScript in a bunch of different-looking ways.

Before you go, let’s do a quick recap.

Conclusion

Today you learned how to calculate the average of an array in JavaScript.

To recap, the average is used in statistics to describe the centrality of a dataset.

To find the average (the mean), sum up the values and divide the sum by the number of values.

In JavaScript, there is a bunch of ways in which you can find the average. In this guide, you saw three common examples:

The latter approach is a bit tricky to wrap your head around as a beginner. However, it is a really short and concise way to get the job done.

Источник

Оцените статью