Number sum in typescript is resulting in NaN

0

I am making a code to get the average values of a list, however the result is 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 perform sum in 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?

    
asked by anonymous 07.03.2018 / 20:14

2 answers

0

With the code you passed you can not be sure that the return of the getCredit() method is really a number in all cases. However, it follows an example of a code functionally equal to yours.

Note that this code will return a NaN in case the array is empty. Maybe this is the case in your application, you could check in advance whether 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));
    
07.03.2018 / 20:38
0

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

    
08.03.2018 / 02:22