mafortis
mafortis

Reputation: 7128

How to sum jquery map values

I have map function to get selected checkboxes and I need to sum values of this map but I get NaN

Code

var prices = $("input:checkbox:checked").map(function(){
  return $(this).val();
}).get();


var number = prices;
var nf = new Intl.NumberFormat('en-US', {
  maximumFractionDigits:0, 
  minimumFractionDigits:0
});
var formattedNumber = nf.format(number);

$('.paybutton').append('<a class=" btn-link" href="">'+ nf.format(prices)+'</a>');

console.log(prices); returns data below when i play with check boxes so i guess my map is OK.

Array [ "5467457" ]
Array [ "57558", "5467457" ]
Array [ "57558" ]
Array []

In other hand my appended data is like:

5,467,457NaN57,55805,467,4570

And it keeps this way as long as i play with check boxes.

Question

  1. How can I have sum of my function in + nf.format(prices)+?

Upvotes: 0

Views: 2192

Answers (3)

Twisty
Twisty

Reputation: 30893

Give this a try:

var prices = $("input:checkbox:checked").map(function(){
  return $(this).val();
}).get();

function formatCurr(arr){
  var n = 0;
  if(arr.length){
    $.each(arr, function(k, v){
      n += parseFloat(v);
    });
  }
  return n.toLocaleString('en-US');
}

$('.paybutton').append('<a class=" btn-link" href="">'+ formatCurr(prices) +'</a>');

May not be the only way to do this. I suspect this is one of a few. Input is [ "5467457" ], Output is 5,467,457.

Working Example

$(function() {
  function formatCurr(arr) {
    var n = 0;
    if (arr.length) {
      $.each(arr, function(k, v) {
        n += parseInt(v);
      });
    }
    return n.toLocaleString('en-US');
  }
  console.log(formatCurr(["5467457"]));
  console.log(formatCurr(["57558", "5467457"]));
  console.log(formatCurr(["57558"]));
  console.log(formatCurr(["9876543210"]));
  console.log(formatCurr(["1001", "2002", "3003", "4004", "5005"]));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Hope it helps.

Upvotes: 0

Umair Abid
Umair Abid

Reputation: 1463

Your approach seems to be correct, but I must say jquery map works in a weird way, those return Array's had me thinking for a while but then I realised it was map which was returning values in array and hence multiple arrays. I was able to get the sum of checked checkboxes using plain javascript and Mihir suggestion. It looks like follows

const checkboxes = document.querySelectorAll('input[type=checkbox]');

// this could have been avoided if NodeList had map method
const prices = [];

checkboxes.forEach(chkbox => prices.push(chkbox.checked && Number(chkbox.value)));

const totalSum = prices.reduce((a, b) => a + b, 0);

console.log(totalSum)

I tested it few times seems to be working fine

Upvotes: 0

Mihir Bhende
Mihir Bhende

Reputation: 9055

You are passing an array to nf.format(number);

instead do this :

function add(a, b) {
    return a + b;
}

var number = prices.reduce(add, 0);

and then do nf.format(number);

Upvotes: 1

Related Questions