daniel-j-guenther
daniel-j-guenther

Reputation: 13

Average Calculator for an Array (null arguments returns NaN)

Uses rest parameter and for...of loop for an array...

function average(...nums) {
    let total = 0;
    for(const num of nums) {
      total += num;
    }
    let avr = total / arguments.length;
    return avr;
}

console.log(average(2, 6));
console.log(average(2, 3, 3, 5, 7, 10));
console.log(average(7, 1432, 12, 13, 100));
// returns NaN - required to return 0. 
console.log(average());

Problem: for no arguments - console.log(average()); - Returns NaN where the correct answer must be 0.

Any good shorthand solution here?

Upvotes: 1

Views: 134

Answers (3)

Yak O'Poe
Yak O'Poe

Reputation: 822

It's not very elegant but...

const average = (...arr) => arr.reduce( ( acc, current ) => acc + current, 0 ) / (arr.length || 1) ;

console.log(average(2, 6));
console.log(average(2, 3, 3, 5, 7, 10));
console.log(average(7, 1432, 12, 13, 100));
console.log(average());

Upvotes: 0

down
down

Reputation: 76

You could just check arguments.length at the start of the function. Something like:

function average(...nums) {
    //check if no args are passed & return 0
    if(arguments.length === 0) return 0;
    //else
    let total = 0;
    for(const num of nums) {
    total += num;
    }
    let avr = total / arguments.length;
    return avr;
}

Upvotes: 3

Prashant
Prashant

Reputation: 151

Modify the function as -

function average(...nums) {
    if(nums.length === 0){
        return 0;
    }
    let total = 0;
    for(const num of nums) {
        total += num;
    }
    let avr = total / arguments.length;
    return avr;
}

Upvotes: 4

Related Questions