Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count comma separated values in javascript

Tags:

javascript

php

Here i've a number of values that are comma separated. now i just want to count them.

Click to load image

the values are

"160,159,158,157,156,155,143,141,140,139"

like:

160: 1
159: 2
158: 3 and so on..

And here in my try

 var checkValues = $('input[name=checkboxlist]:checked').map(function()
                   {
                        return $(this).val();
                   }).get();
 var i = '"'+checkValues+'"'.split(',');
 alert(i);

Please guide me, where am i going wrong?

like image 761
Bug Inspector Avatar asked Dec 12 '25 05:12

Bug Inspector


2 Answers

I think you want the count not the sum.

split it on , and get the length

var val="160,159,158,157,156,155,143,141,140,139";
console.log("Count : ",val.split(",").length);

If you want the index of each value and count

then use

var val="160,159,158,157,156,155,143,141,140,139";
val.split(",").forEach( (x,y) => console.log(x," : ",y+1));

the y+1 is there because y is position and starts from 0

like image 178
Sagar V Avatar answered Dec 14 '25 19:12

Sagar V


var numbers = "160,159,158,157,156,155,143,141,140,139";

// If you just want to count them :
var count = numbers.split(',').length;
console.log(count);

// If you want to link a value and its 'index'
var result = {};

numbers.split(',').forEach((e, i) => { 
  result[e] = i + 1;
});

console.log(result);
like image 41
Serge K. Avatar answered Dec 14 '25 17:12

Serge K.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!