snippetjavascriptTip
Perform math operations on arrays of numbers in JavaScript
Viewed 0 times
javascriptarraysnumbersperformoperationsmath
Problem
Numeric arrays are a very common data structure, one that you will often need to perform certain operations on. Most commonly, you will need to calculate the sum, average, product or median of the numbers in an array. Let's take a look at how you can do this, using JavaScript.
> [!NOTE]
>
> Some of the following functions are variadic, meaning they can accept any number of arguments. You can use the spread operator (
The sum of an array is the result of adding all the numbers in the array together.
> [!NOTE]
>
> Some of the following functions are variadic, meaning they can accept any number of arguments. You can use the spread operator (
...) to pass an array of numbers to these functions.The sum of an array is the result of adding all the numbers in the array together.
Solution
const sum = (...arr) =>
[...arr].reduce((acc, val) => acc + val, 0);
sum(1, 2, 3, 4); // 10
sum(...[1, 2, 3, 4]); // 10>
> Some of the following functions are variadic, meaning they can accept any number of arguments. You can use the spread operator (
...) to pass an array of numbers to these functions.The sum of an array is the result of adding all the numbers in the array together.
Using
Array.prototype.reduce(), you can easily calculate the sum of an array of numbers, by adding each value to an accumulator, initialized with a value of 0.The average of an array is the result of adding all the numbers in the array together and then dividing the resulting sum by the length of the array.
You can use the same technique as summing an array, then use
Array.prototype.length to divide the resulting sum by the length of the array.Code Snippets
const sum = (...arr) =>
[...arr].reduce((acc, val) => acc + val, 0);
sum(1, 2, 3, 4); // 10
sum(...[1, 2, 3, 4]); // 10const average = (...arr) =>
[...arr].reduce((acc, val) => acc + val, 0) / arr.length;
average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2const prod = (...arr) =>
[...arr].reduce((acc, val) => acc * val, 1);
prod(1, 2, 3, 4); // 24
prod(...[1, 2, 3, 4]); // 24Context
From 30-seconds-of-code: numeric-array-math-operations
Revisions (0)
No revisions yet.