sum of two array in Node.js

Issue

I try to Sum below two Arrays and use below two Methods:


    A = [
                    25.8,                 27,
      24.099999999999998, 30.070000000000004,
                    34.3, 34.300000000000004,
                    34.3,                 33,
                    29.2,               29.2,
                    27.6, 28.999999999999996,
      29.310000000000002, 27.000000000000004
    ]
    
    B = [
      '0.00387000', '0.00472000',
      '0.00534000', '0.00460000',
      '0.00060000', '0.00032000',
      '0.00053000', '0.00327000',
      '0.00217000', '0.00217000',
      '0.00460000', '0.00415000',
      '0.00852000', '0.02241000'
    ]

Method 1


    //sum array function
    Array.prototype.SumArray = function (arr) {
        var sum = [];
        if (arr != null && this.length == arr.length) {
            for (var i = 0; i < arr.length; i++) {
                sum.push(this[i] + arr[i]);`enter code here`
            }
        }
        return sum;
    }
    
    C = A.SumArray(B);
    console.log (C)

Method 2


    var C = A.map(function (num, idx) {
      return num + B[idx];
    });

But the console result is the same as below:


    [
    '25.80.00387000',
    '270.00472000',
    '24.0999999999999980.00534000',
    '30.0700000000000040.00460000',
    '34.30.00060000',
    '34.3000000000000040.00032000',
    '34.30.00053000',
    '330.00327000',
    '29.20.00217000',
    '29.20.00217000',
    '27.60.00460000',
    '28.9999999999999960.00415000',
    '29.3100000000000020.00852000',
    '27.0000000000000040.02241000'
    ]

How can I add two array to make new Array like this:

[
‘25.80387000’,
‘27.00472000’,
.
.
.
.
.
.
]

Could anyone help to let me know why and how to fix this?

Solution

A contains numbers while B contains strings. You want to cast to numbers first to make the computation, and then cast the result to string to get a string; you can use .toFixed to get a given number of precisiong (according to your expected output).

    A = [
                    25.8,                 27,
      24.099999999999998, 30.070000000000004,
                    34.3, 34.300000000000004,
                    34.3,                 33,
                    29.2,               29.2,
                    27.6, 28.999999999999996,
      29.310000000000002, 27.000000000000004
    ]
    
    B = [
      '0.00387000', '0.00472000',
      '0.00534000', '0.00460000',
      '0.00060000', '0.00032000',
      '0.00053000', '0.00327000',
      '0.00217000', '0.00217000',
      '0.00460000', '0.00415000',
      '0.00852000', '0.02241000'
    ]
    
    C = A.map((a,i)=> (a+Number(B[i])).toFixed(8))
    console.log(C)

Answered By – Vincent

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.