How can we do find average of an array using spread operator?
I tried using different ways but didn’t got what I expected.
I actually tried this way but didn’t got any result:
let arr = [1, 2, 3, 4, 5];
console.log(...arr);
let sum = (...arr) => arr.reduce((a, b) => a + b);
console.log(sum);
avg = sum / (arr.length);
console.log(avg);
5
Answers
Actually your
sum
is a function, not a numeric value.Please try:
You made the function to get the sum:
let sum = (...arr) => arr.reduce((a, b) => a + b);
But you didn’t actually apply it yet, so there is no result. To apply it:
let totalSum = sum(...arr);
Then, to calculate the average:
let avg = totalSum / arr.length;
You can find the average of an array using the spread operator and the reduce function. Here’s a concise example:
In your code, the spread operator (
...arr
) is not needed for calculating the sum. The correct usage is demonstrated in the example above.You are never calling your arrow function and you cannot divide a function by a number. Call your function to get a numeric value:
Since the function is immediately invoked, you might as well just drop it:
You can try this:
Hope this helps.