Sum of number in typescript is resulting in Nan

Asked

Viewed 1,064 times

0

I’m making a code to get the average values of a list, however the result is being Nan (not a number).

import { SimpleTableAnalysis } from '../model/SimpleTableAnalysis'
import { UserInfo } from '../model/UserInfo';

export class MeanAnalysis implements SimpleTableAnalysis {

    public analysis(userInfoList: Array<UserInfo>): number{

        var sum: number = 0.0;

        userInfoList.forEach(userInfo => sum += userInfo.getCredit() );

        return sum/(userInfoList.length);
    }
}

The error happens inside the foreach, the code recognizes the value of the method 'getCredit()', which returns number, and it is possible to sum it, however with the variable 'sum' (external variable to foreach) returns me Nan even in a normal for.

Follow the conversion to javascript:

"use strict";
Object.defineProperty(exports, "__esModule", {
    value: !0
});
var MeanAnalysis = function() {
    function e() {}
    return e.prototype.analysis = function(e) {
        var n = 0;
        return e.forEach(function(e) {
            return n += e.getCredit()
        }), n / e.length
    }, e
}();
exports.MeanAnalysis = MeanAnalysis;

How do I fix this?

2 answers

1

With the code you passed, you can’t be sure if the return of the method getCredit() is actually a number in all cases. However, it follows an example of a code functionally equal to your.

Note that, this code will return a NaN in the case of array be vázio. Maybe that’s the case in your application, you could check beforehand if the array.length === 0 and return a valid value, or play a Error if necessary.

var nums = [
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10
];

function media(numArray) {
  if(numArray.length === 0) return 0;
  return numArray.reduce((sum, item) => sum += item, 0) / numArray.length;
}

console.log(media(nums));

0

I was able to solve the problem, the error was that I was searching for data from a file. csv, but I remembered to treat only the header and not the blank lines which resulted in some Nan elements.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.