skip to Main Content

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


  1. Actually your sum is a function, not a numeric value.

    Please try:

    let sum = arr.reduce((a, b) => a + b);
    
    Login or Signup to reply.
  2. 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;

    Login or Signup to reply.
  3. You can find the average of an array using the spread operator and the reduce function. Here’s a concise example:

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

    In your code, the spread operator (...arr) is not needed for calculating the sum. The correct usage is demonstrated in the example above.

    Login or Signup to reply.
  4. You are never calling your arrow function and you cannot divide a function by a number. Call your function to get a numeric value:

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

    Since the function is immediately invoked, you might as well just drop it:

    const arr = [1, 2, 3, 4, 5];
    const sum = arr.reduce((a, b) => a + b, 0);
    // ...
    
    Login or Signup to reply.
  5. You can try this:

    function findAverage(...numbers) {
        // the formula for getting average is (sum/total)
        let sum = 0;
        numbers.forEach(number => {
            sum += number;
        });
        const total = numbers.length;
        const average = sum / total;
        return average;
    }
    
    let arr = [1, 2, 3, 4, 5];
    findAverage(...arr); // returns 3
    // or
    findAverage(1,2,3,4,5) // returns 3
    

    Hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search