Как сложить элементы массива js
Перейти к содержимому

Как сложить элементы массива js

  • автор:

Javascript Sum Array

By Payal UdhaniPayal Udhani

Javascript Sum Array

Introduction to Javascript Sum Array

In javascript, we can calculate the sum of the elements of the array by using the Array.prototype.reduce() method. The reduced method for arrays in javascript helps us specify a function called reducer function that gets called for each of the elements of an array for which we are calling that function. The output of the reduce() method is a single value that is returned as a collection of all the operations performed on each of the element of the array that is defined in the reducer function. We can use the reduce() function to retrieve the sum of all the array elements by writing a corresponding reducer function that will add the elements of the array and call this reducer function inside the reduce method.

In this article, we will learn about how sum of array elements can be calculated using the standard old way of for loop and then by the new optimized, efficient and convenient way of reducing () method along with its syntax and examples.

Web development, programming languages, Software testing & others

Python TutorialC SharpJavaJavaScript

C Plus PlusSoftware TestingSQLKali Linux

Old Way of the Calculating Sum of Array Elements

Before the introduction of the reduce() method, we used to calculate the sum of array elements using the for a loop. We would iterate the loop from 0 to the length of the array as indexing of the array starts from 0 and then calculate the sum inside the for a loop. Let us consider one example where we will calculate the total salary of all the employees where the salary of each employee is stored in the array salaries as shown below.

Code:

that gives the following output after execution:

javascript sum array 2

We can see how the totalSalary variable is added with each of the value of the elements of the salaries array by iterating the for loop to retrieve the sum of the array elements that is the total salary of all the employees.

Array.prototype.reduce() Method

Now, we will learn about the reduce() method that will be used for calculating the sum of the array elements. Let us begin by studying its syntax.

  • callback – It is also called the reducer function that is a callback or function that executes for each of the elements of the array. Note that the first value in the array is not considered if we do not supply any initial value in the valueInBeginning parameter.
  • accumVariable – It is the variable that stores the result to be returned after the reducer function is executed for all of the elements of the array. It has the value that was returned at the time of the last invocation of the reduce() method or the valueInBeginning parameter value if specified. This is the required parameter to the callback function and needs to be mentioned while using it.
  • curValue – It is a required parameter of the reducer function callback and stands for the current element of the array for which the reducer function is being executed.
  • Index – It is the index of the current element that is being processed and for which the reducer function is getting executed. It has the initial value as zero if valueInBeginning is specified else has 1 value as the initial value in it. It is optional.
  • yourArray – This is the array for which the reducer function needs to be called for each of its elements. It is an optional parameter.
  • valueInBeginning – It is the initial value that is the value that will be used as the first parameter to the function. If not specified, then the first element of the array at the zero indexes will be used as the accumulator value in the beginning and the value of the first element of the array will be skipped for the curValue variable. If the reduce method is called using the empty brackets without any parameters for a blank array without specifying the value in beginning i.e initial value then javascript will throw a TypeError.
  • Return value – The value that is returned by the reducer function/callback is a single value that is the result of the accumulation of all the values that were resulted by executing the reducer function for each of the elements of the array.

Example

Let us consider a simple example of a previous scenario where we wanted to calculate the total salary of all the employees stored in the array format. But now, we will use the reduce() method to calculate the sum instead pf for a loop as shown below.

Code:

that gives the following output after execution:

javascript sum array 1

Let us consider one more example where we will calculate the total expenditure where values in the array are stored in key-value pair where the key is the expenditure as shown below.

Code:

<!DOCTYPE html> <html> <body> <p>Demostration of using Array.prototype.reduce() method for calculationg sum of array elements</p> <p ></p> <script> // sums to 1015 let valueInBeginning = 0; let totalExpenditure = [, , ].reduce( (accumVariable, curValue) => accumVariable + curValue.expenditure , valueInBeginning ) document.getElementById(«demo»).innerHTML = «Total Expenditure alignnone wp-image-427670 size-full» svg+xml,%3Csvg%20xmlns=’http://www.w3.org/2000/svg’%20viewBox=’0%200%20635%2073’%3E%3C/svg%3E» alt=»total expenditure» width=»635″ height=»73″ data-lazy-srcset=»https://cdn.educba.com/academy/wp-content/uploads/2020/10/javascript-sum-array.png 635w, https://cdn.educba.com/academy/wp-content/uploads/2020/10/javascript-sum-array-300×34.png 300w» data-lazy-sizes=»(max-width: 635px) 100vw, 635px» data-lazy-src=»https://cdn.educba.com/academy/wp-content/uploads/2020/10/javascript-sum-array.png» />

We can find the total expenditure by using the reduced function as shown above by considering the element. expenditure value.

Conclusion

We can calculate the sum of the array elements by using the standard for loop. The most recent, optimized, and efficient way of calculating the sum of array elements is the use the reduce() method in javascript and write a reducer function or callback for it that will return the accumulated value.

How to get the sum of an array in JavaScript

Get Educative’s popular interview prep course for free.

In this shot, we will discuss three methods you can use to get the total of a given array in JavaScript.

First, we’ll use the traditional for loop. Secondly, we’ll use forEach , an array-like method, and lastly, we’ll make use of for. of .

In this shot, our array example is [1, 4, 0, 9, -3] , and the expected output is 11 .

1. Using the traditional for loop

In this method, you iterate and add each item until you reach the last item.

How to find the sum of an array of numbers

I thought $.each might be useful, but I’m not sure how to implement it.

59 Answers 59

This’d be exactly the job for reduce .

If you’re using ECMAScript 2015 (aka ECMAScript 6):

Isn’t that pretty? 🙂

Florian Margaine's user avatar

Recommended (reduce with default value)

Array.prototype.reduce can be used to iterate through the array, adding the current element value to the sum of the previous element values.

Without default value

You get a TypeError

Prior to ES6’s arrow functions

Non-number inputs

If non-numbers are possible inputs, you may want to handle that?

Non-recommended dangerous eval use

We can use eval to execute a string representation of JavaScript code. Using the Array.prototype.join function to convert the array to a string, we change [1,2,3] into «1+2+3», which evaluates to 6.

Of course displaying an alert isn’t the worst thing that could happen. The only reason I have included this is as an answer Ortund’s question as I do not think it was clarified.

Why not reduce? It’s usually a bit counter intuitive, but using it to find a sum is pretty straightforward:

Peter Mortensen's user avatar

Anyone looking for a functional oneliner like me?

Here’s the oneliner for modern JS:

(If you happen to have to support ye olde IE without arrow functions:)

Note that 0 is the initial value here, so you can use that as offset if needed. Also note that this initial value is needed, otherwise calling the function with an empty array will error.

If you happen to be using Lodash you can use the sum function

simhumileco's user avatar

David says Reinstate Monica's user avatar

This is possible by looping over all items, and adding them on each iteration to a sum -variable.

JavaScript doesn’t know block scoping, so sum will be accesible:

The same as above, however annotated and prepared as a simple function:

Peter Mortensen's user avatar

onhout's user avatar

OK, imagine you have this array below:

Let’s start looking into many different ways to do it as I couldn’t find any comprehensive answer here:

1) Using built-in reduce()

2) Using for loop

3) Using while loop

4) Using array forEach

and call it like this:

It’s not recommended to prototype something like this to Array.

Alireza's user avatar

You can also use reduceRight.

which results output as 21.

You can try the following code:

Md.Shakil Shaikh's user avatar

A standard JavaScript solution:

This works for me (the result should be 5). I hope there is no hidden disadvantage in this kind of solution.

Simon Baumgardt-Wellander's user avatar

I am a beginner with JavaScript and coding in general, but I found that a simple and easy way to sum the numbers in an array is like this:

Basically, I wanted to contribute this because I didn’t see many solutions that don’t use built-in functions, and this method is easy to write and understand.

If you care about performance, define a function that uses a for -loop.

Benchmark

I benchmarked a selection of implementations using benchmark.js (typescript version):

In chrome 104, the for -loop-based implementations are the fastest:

Firefox 104 shows similar behaviour:

Discussion

Implementations defining an anonymous function are generally slower because creating an anonymous function is a significant overhead. When running the benchmark with a large array, e.g., with length 1000 instead of 100, the difference between reduce and the for -loop-based implementations becomes insignificant in chrome.

Chrome’s V8 engine knows how to inline simple anonymous functions in reduce since the reduce test case is much faster than the predefined reduce test case. Firefox seems to try something similar but is less efficient in doing so. Non-inlined function calls are pretty slow in js since the call stack is less efficient than the call stack in compiled software.

Similar to reduce , the forEach — and jquery -based implementations use anonymous functions and are relatively slow. lodash has a specialized sum implementation, but it is (as of v4.0.0) implemented as a special case of sumBy , which is relatively inefficient.

eval is the by far slowest test case. This makes sense since constructing the string using concatenations might cause several dynamic allocations (which are slow). Next, the parser has to be invoked and only then can the code be finally executed.

I’ve included some recursive implementations because some people on the internet claim that recursion is faster than loops in js. I can’t reproduce their example — using benchmark.js , recursion is very slow, and when using console.time with a loop, both functions take the same time. When calculating the sum, as expected, recursion is much slower than loops, probably due to intense usage of the js call stack.

The naive implementation would be manually adding all 100 elements of the array. While being quite inconvenient, this is the fastest implementation. But, luckily, for -loops come very close. Adding a single function call around the loop doesn’t harm the performance. Therefore, you can feel free to use the utility function from above.

I have no explanation why the while loop is slower than the for loop. Iterating the array in reverse doesn’t seem to be the problem here.

Найти сумму всех значений массива в JavaScript

В этом посте мы обсудим, как найти сумму всех значений массива в JavaScript.

1. Использование Array.prototype.reduce() функция

The reduce() можно использовать для выполнения функции редуктора для каждого элемента массива. Чтобы вычислить сумму всех значений массива, функция редуктора должна добавить текущее значение элемента к уже вычисленной сумме предыдущих значений.

Подводя итог, значения, содержащиеся в массиве, вы должны указать значение по умолчанию для reduce() метод, иначе код выдаст TypeError на пустой массив. Это показано ниже с использованием анонимной функции.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *