Bug Inspector
Bug Inspector

Reputation: 301

How to count comma separated values in javascript

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?

Upvotes: 3

Views: 9622

Answers (6)

Saurabh Yadav
Saurabh Yadav

Reputation: 3386

var values = "160,159,158,157,156,155,143,141,140,139";
var final  = values .split(',').reduce(function(accumulator, currentValue, 
 currentIndex) {
      accumulator[currentValue] = currentIndex;
       return accumulator;
},{});

Hope it helps you!

Upvotes: 0

Serge K.
Serge K.

Reputation: 5323

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);

Upvotes: 2

Sagar V
Sagar V

Reputation: 12478

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

Upvotes: 7

philipp
philipp

Reputation: 16515

To count the number of occurrences of each value you can use [].reduce()

const result = "160,159,158,157,156,155,143,141,140,139"
   .split(/,/)
   .reduce((counter, val) => {
      if (!counter.hasOwnProperty(val)) counter[val] = 0;
      counter[val]++;
      return counter;
    }, {});

Upvotes: 0

Miroslav Jonas
Miroslav Jonas

Reputation: 6637

You are missing the brackets. Chaining function has priority over standard numeric operation. Should be:

var i = ('"'+checkValues+'"').split(',');

To group and count each distinct value you can use approaches other proposed, like:

var result = i.reduce(function(prev, curr){
  if (prev[curr]) { prev[curr]++; }
  else { prev[curr] = 1; }
  return prev;
}, {});

Upvotes: 0

naortor
naortor

Reputation: 2089

You can do it by turning it to array using String.split,

and then use reduce to count your values

var ans = "160,159,158,157,156,155,143,141,140,140,139".split(',').reduce((prev,curr)=>{
  if (prev[curr]) prev[curr]++;
  else prev[curr] = 1;
  
  return prev;
}, {});

console.log(ans);

Upvotes: 0

Related Questions