0

I try to use map and reduce together to build a function where it loops through array of object and do some math but I got NAN. Why?

function getTotal(){
 var obj = [
  {
    "name": "item 1",
    "discount_price": 86.9,
    "qty": 1,
  },
  {
    "name": "item 2",
    "discount_price": 11.9,
    "qty": 1,
  }
];
  
          return obj.map(function(x){;return x.discounted_price * x.qty}).reduce(function(a,b){return a + b});

 
 }

$('p').text(getTotal());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<p></p>
Jennifer
  • 905
  • 9
  • 20

1 Answers1

0

Object property is discount_price not discounted_price, since x.discounted_price is undefined all array values are NaN (When and why number evaluates to NaN, after multiplying, in Javascript?).

function getTotal() {
  var obj = [{
    "name": "item 1",
    "discount_price": 86.9,
    "qty": 1,
  }, {
    "name": "item 2",
    "discount_price": 11.9,
    "qty": 1,
  }];

  return obj.map(function(x) {;
    return x.discount_price * x.qty
    // -------------^------ bug is here
  }).reduce(function(a, b) {
    return a + b
  });


}

$('p').text(getTotal());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<p></p>

Or you can avoid the map() method

function getTotal() {
  var obj = [{
    "name": "item 1",
    "discount_price": 86.9,
    "qty": 1,
  }, {
    "name": "item 2",
    "discount_price": 11.9,
    "qty": 1,
  }];

  return obj.reduce(function(a, b) {
    return a.discount_price * a.qty + b.discount_price * b.qty
  });

}

$('p').text(getTotal());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<p></p>

For the problem with precision refer : How to deal with floating point number precision in JavaScript?

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188