skip to Main Content

I m getting values from multiple radio button and storing it into variables as a comma seperated number.

var coef = "1, 2, 3, 4";

output I want is multiplication of of all numbers;

total = 24

I m trying to implement it in javascript/jquery. Any help?

3

Answers


  1. You could try something like this:

    var coef = "1, 2, 3, 4";
    var total = coef.trim().split(",").reduce((accumulator, value) => accumulator * value, 1);
    

    If array

    var total = coef.reduce((accumulator, value) => accumulator * value, 1);
    

    Demo

    var coef = "1, 2, 3, 4";
    var total = coef.trim().split(",").reduce((accumulator, value) => accumulator * value, 1);
    console.log(total)
    Login or Signup to reply.
  2. You can solve this with split and reduce if you pass in a comma separated string:

    var coef = "1, 2, 3, 4";
    
    var total = coef.split(',').reduce( (a, b) => a * b );
    
    console.log(total);

    If you pass in an array, you don’t need to split:

    var coef = [1, 2, 3, 4];
    
    var total = coef.reduce( (a, b) => a * b );
    
    console.log(total);
    Login or Signup to reply.
  3. You could use .split() and .forEach() methods :

    var coef = "1, 2, 3, 4";
    var product = 1;
    coef.split(",").forEach(factor => product *= factor);
    console.log(product);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search