- Как сложить все элементы массива js
- JavaScript: 6 Ways to Calculate the Sum of an Array
- Using Array.reduce() method
- Using a classic For loop
- Using modern For/Of loop
- Using the map() method
- Using a While loop
- Using a forEach loop
- Conclusion
- Javascript сложение элементов массивов
- # Table of Contents
- # Get the Sum of an Array of Numbers in JavaScript
- # Creating a reusable function
- # Get the Sum of an Array of Numbers using a for. of loop
- # Get the Sum of an Array of Numbers using Array.forEach()
- # Get the Sum of an Array of Numbers using a for loop
- # Get the Sum of an Array of Numbers using a while loop
- # Get the Sum of an Array of Numbers using lodash
- # Additional Resources
- Сумма элементов массива в JavaScript
- Использование цикла for
- Использование метода reduce
- Использование метода forEach
Как сложить все элементы массива js
Можно использовать обычный цикл, но есть более красивое решение. Метод reduce() , принимает в качестве аргумента массив и колбек функцию, которая применяется к каждому элементу массива и таким образом позволяет найти их сумму. Вот пример:
const numbers = [1, 2, 3, 4]; const sumOfNumbers = numbers.reduce((acc, number) => acc + number, 0); console.log(sumOfNumbers); // => 10
А за такое использование map могут и побить. Если уж и хочется из цикла что-то менять снаружи (что почти всегда плохая идея), то для этого используют forEach . Map возвращает значение, которое должно быть использовано. И map не должен менять ничего извне. Иначе код становится сложноподдерживаемым.
Помимо стандартного перебора значений и красивого метода reduce(), можно воспользоваться функцией высшего порядка map:
const numbers = [1, 2, 3]; let sum = 0; numbers.map((item) => sum += item); console.log(sum); // => 6
И для любителей библиотеки Lodash доступен метод _.sum():
const numbers = [1, 2, 3]; console.log(_.sum(numbers)); // => 6
JavaScript: 6 Ways to Calculate the Sum of an Array
This practical, succinct article walks you through three examples that use three different approaches to find the sum of all elements of a given array in Javascript (suppose this array only contains numbers). Without any further ado, let’s get started.
Using Array.reduce() method
If you’re using modern Javascript (ES6 and beyond), this might be the neatest and quickest solution.
// define a reusable function const calculateSum = (arr) => < return arr.reduce((total, current) =>< return total + current; >, 0); > // try it console.log(calculateSum([1, 2, 3, 4, 5]));
The reduce() method executes a reducer function for elements of an array. It returns the accumulated result from the last call of the callback function. Below is the syntax:
array.reduce(function(total, current, index, arr), initialValue)
- total (required): The initial value, or the previously returned value of the function
- current (required): The current element
- current (optional): The index of the current element
- arr (optional): The array that the current element belongs to
Javascript is interesting, and it also has another method quite similar to the reduce() method, named reduceRight() . You can get the sum of a numeric array with only a single line of code like this:
const sum = [1, 2, 3, 4, 5].reduceRight((acc, cur) => acc + cur, 0); console.log(sum);
Using a classic For loop
This is an easy-to-understand approach and has been used for decades. However, the code is a bit longer.
// define a reusable function function calculateSum(arr) < var sum = 0; for (var i = 0; i < arr.length; i++) < sum += arr[i]; >return sum; > // try it console.log(calculateSum([1, 2, 3, 4]));
Using modern For/Of loop
This approach also uses a loop but is more concise than the previous one. Like the Array.reduce() method, for/of was added to ES6 (JS 2015).
const arr = [9, 8, 7, 6, 5]; let sum = 0; for (let e of arr) < sum += e; >console.log(sum);
Using the map() method
The Array.map() method is new in ES6 and beyond. This one is very useful when you have to deal with an array, including finding the sum of its elements.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; let sum = 0 arr.map(e => sum += e) console.log(sum);
Using a While loop
Another way to sum the elements of an array for your reference (basically, it’s quite similar to other methods of using loops).
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let sum = 0; let i = -1; while (++i < arr.length) < sum += arr[i]; >console.log(sum);
Using a forEach loop
Just another kind of loop in Javascript. Here’s how to make use of it to calculate the total value of a given array:
const array = [1, 2, 3, 4]; let sum = 0; array.forEach(e => < result += e; >) console.log(result);
Conclusion
We’ve walked through several ways to get the sum of all elements of a given array in Javascript. Although just one method is enough, knowing the existence of other methods also helps you a lot in mastering the art of programming. Good luck and happy coding!
Javascript сложение элементов массивов
Last updated: Dec 26, 2022
Reading time · 5 min
# Table of Contents
# Get the Sum of an Array of Numbers in JavaScript
To get the sum of an array of numbers:
- Use the Array.reduce() method to iterate over the array.
- Set the initial value in the reduce method to 0 .
- On each iteration, return the sum of the accumulated value and the current number.
Copied!const arr = [5, 15, 45]; const sum = arr.reduce((accumulator, value) => return accumulator + value; >, 0); console.log(sum); // 👉️ 65
The function we passed to the Array.reduce method gets called for each element in the array.
We initialized the accumulator variable to 0 because that’s what we passed as the second argument to the reduce() method.
After the last iteration, the sum variable stores the sum of the numbers in the array.
# Creating a reusable function
If you have to calculate the sum of arrays often, define a reusable function.
Copied!function calculateSum(array) return array.reduce((accumulator, value) => return accumulator + value; >, 0); > const result1 = calculateSum([1, 2, 3]); console.log(result1); // 👉️ 6 const result2 = calculateSum([1, 2, 3, 4]); console.log(result2); // 👉️ 10
The calculateSum() function takes an array as a parameter and calculates the sum of the numbers in the array.
You can also shorten the function we passed to the reduce() method by using an implicit return statement.
Copied!function calculateSum(array) return array.reduce((accumulator, value) => accumulator + value, 0); > const result1 = calculateSum([1, 2, 3]); console.log(result1); // 👉️ 6 const result2 = calculateSum([1, 2, 3, 4]); console.log(result2); // 👉️ 10
The arrow function in the example uses an implicit return.
An alternative and perhaps simpler approach is to use a for. of loop.
# Get the Sum of an Array of Numbers using a for. of loop
This is a three-step process:
- Declare a sum variable and initialize it to 0 .
- Use the for. of loop to iterate over the array.
- On each iteration, reassign the sum variable to its current value plus the value of the current element.
Copied!const arr = [5, 15, 45]; let sum = 0; for (const value of arr) sum += value; > console.log(sum); // 👉️ 65
If you need to handle non-numeric values, use the typeof operator.
Copied!// 👇️ array contains non-numeric values const arr = ['a', 5, 'b', 15, 'c', 45]; let sum = 0; for (const value of arr) if (typeof value === 'number') sum += value; > > console.log(sum); // 👉️ 65
The array in the code sample also contains non-numeric values, so we used the typeof operator to check if each value is a number before adding it to the total.
The for. of statement is used to loop over iterable objects like arrays, strings, Map , Set and NodeList objects and generators .
Notice that we declared the sum variable using the let keyword. Had we declared the variable using const , we wouldn’t be able to reassign it.
On each iteration, we reassign the sum variable to its current value plus the value of the current element.
If you have to do this often, extract the logic into a reusable function.
Copied!function calculateSum(array) let total = 0; for (const value of array) total += value; > return total; > const result1 = calculateSum([1, 2, 3]); console.log(result1); // 👉️ 6 const result2 = calculateSum([1, 2, 3, 4]); console.log(result2); // 👉️ 10
The calculateSum() function takes an array as a parameter, calculates the sum of its values and returns the result.
Alternatively, you can use Array.forEach() .
# Get the Sum of an Array of Numbers using Array.forEach()
This is a three-step process:
- Declare a new sum variable and initialize it to 0 .
- Use the Array.forEach() method to iterate over the array.
- On each iteration, reassign the value of the sum variable to its current value plus the array element.
Copied!const arr = [5, 15, 45]; let sum = 0; arr.forEach(value => sum += value; >); console.log(sum); // 👉️ 65
The function we passed to the Array.forEach method gets called with each element in the array.
On each iteration, we reassign the value of the sum variable to its current value plus the value of the current array element.
The sum variable stores the sum of the values in the array after the last iteration.
If you have to calculate the sum of an array’s elements often, define a reusable function.
Copied!function calculateSum(array) let total = 0; array.forEach(value => total += value; >); return total; > const result1 = calculateSum([1, 2, 3]); console.log(result1); // 👉️ 6 const result2 = calculateSum([1, 2, 3, 4]); console.log(result2); // 👉️ 10
The calculateSum() function takes an array as a parameter, calculates the sum of the array’s elements and returns the result.
Alternatively, you can use a basic for loop.
# Get the Sum of an Array of Numbers using a for loop
This is a three-step process:
- Declare a new sum variable and initialize it to 0 .
- Use a for loop to iterate over the array.
- Reassign the value of the sum variable to its current value plus the current array element.
Copied!const arr = [5, 15, 45]; let sum = 0; for (let index = 0; index arr.length; index++) sum += arr[index]; > console.log(sum); // 👉️ 65
We used a basic for loop to iterate over the array.
On each iteration, we use the index to access the current array element and reassign the sum variable.
Which approach you pick is a matter of personal preference. I’d use the Array.reduce() method or a for. of loop as both options are quite direct and intuitive.
# Get the Sum of an Array of Numbers using a while loop
You can also use a while loop to get the sum of an array of numbers.
Copied!const arr = [5, 15, 45]; let sum = 0; let i = -1; while (++i arr.length) sum += arr[i]; > console.log(sum); // 👉️ 65
We initialized the sum and i variables using the let keyword.
Using let is important because variables declared using const cannot be reassigned.
On each iteration of the while loop, we increment the i variable and add the current array element to the total.
# Get the Sum of an Array of Numbers using lodash
If you use the lodash library, you can also use the lodash.sum() method to get the sum of an array of numbers.
Copied!import _ from 'lodash'; console.log(_.sum([1, 2, 3])); // 👉️ 6 console.log(_.sum([10, 20, 30])); // 👉️ 60
If you need to install lodash , run the following command.
Copied!# 👇️ initialize a package.json file if you don't have one npm init -y npm install lodash
The lodash.sum method takes an array as a parameter and computes the sum of the values in the array.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Сумма элементов массива в JavaScript
Часто при работе с JavaScript возникает задача подсчета суммы элементов массива. Например, есть массив чисел [5, 10, 15, 20] и требуется найти сумму его элементов.
Часто при работе с JavaScript возникает задача подсчета суммы элементов массива. Например, есть массив чисел [5, 10, 15, 20] и требуется найти сумму его элементов.
В JavaScript есть несколько способов решения данной задачи.
Использование цикла for
Самый простой и понятный способ — использование обычного цикла for . В нем происходит перебор всех элементов массива и их суммирование.
var numbers = [5, 10, 15, 20]; var sum = 0; for (var i = 0; i < numbers.length; i++) < sum += numbers[i]; >console.log(sum); // 50
Использование метода reduce
Более современный и компактный способ — использование метода reduce . Этот метод применяет функцию к каждому элементу массива (слева направо), чтобы привести его к одному значению.
var numbers = [5, 10, 15, 20]; var sum = numbers.reduce(function(a, b)< return a + b; >, 0); console.log(sum); // 50
Использование метода forEach
Еще один способ — использование метода forEach , который выполняет указанную функцию один раз для каждого элемента в массиве.
var numbers = [5, 10, 15, 20]; var sum = 0; numbers.forEach(function(num) < sum += num; >); console.log(sum); // 50
Все эти способы дают один и тот же результат, поэтому можно выбирать любой, который больше нравится или лучше подходит для конкретной задачи.