Skip to content Skip to sidebar Skip to footer

How To Calculate Numbers In String

I have such string 13-2-10-7-3 where numbers delimited by -. I am wondering what is the best way to calculate the sum of all numbers from the string in javascript?

Solution 1:

Here's a function which will split your string by the -. Then go through all the results and add them.

functionadd(string){ 
    returnstring.split('-').reduce(function(a,b){return+a+(+b); });  
}

This will use a regex to extract the numbers from the string. Then it will add them using .reduce(). not to complicated. The +a+(+b) will convert a and b to JavaScript numbers and then add them. +var will make a variable from a string to a number. This is the shortest method you could achieve as far as I know.

If you can't support the .reduce() function, use the alternate code which should support every browser:

functionadd(string) {
    var strings = string.split('-'),
        sum = 0,i;
    for (i = 0; i < strings.length; i +=1 ) {
        sum += (+strings[i]);
    }
}

SPEED: ~0.062 seconds

Fiddle

Solution 2:

Since the numbers are always separated by - then the best approach is to split them into an array:

About string's split method

var string = '13-2-10-7-3';
numbers = string.split('-');

At this points numbers will be a array of strings, you can't sum them up yet or else you will just concatenate them together. So you should convert them to number.

This is easily done mapping the array elements to numbers

About array's map method

numbers = numbers.map(Number);

Now you can reduce the array to the sum of its elements

About array's reduce method

var result = numbers.reduce(function (a, b) { return a + b; });

All at once:

var string = '13-2-10-7-3';
var numbers = string.split('-').map(Number);
var sum = numbers.reduce(function (a, b) { return a + b; }

Solution 3:

var sum = "13-2-10-7-3".split('-').reduce(function(x, y) {
    returnparseInt(x)+ parseInt(y);
});

Solution 4:

reduce() requires IE9+

I'm using jQuery.each here

var input = '13-2-10-7-3', sum = 0;


$.each(input.split('-'), function(idx, elm) {
  sum += (+elm); // parse string to int using `+` 
});

document.write('The sum of ' + input + ' is ' + sum);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Solution 5:

Try this:

The "split" function turns the delimitedNumbers string into an array of strings. Using the "-" to determine where to split.

Conceptually, the numbers variable would look like ["13"]["2"]["10"]["7"]["3"] after the split.

We then loop through the numbers array, using the parseInt function to convert each element from a string to a number and then add to the current value of the sum variable.

Finally we summon an alert pop-up to display the final sum.

sum = function(){
    var i, len, delimitedNumbers, numbers, sum;

    delimitedNumbers = "13-2-10-7-3";

    numbers = delimitedNumbers.split('-');
    len = numbers.length;

    sum = 0;
    for(i = 0; i < len; i++)
    {
        sum = sum + parseInt(numbers[i]);
    }

    alert("The sum is: " + sum);
  } 

JSFiddle

Post a Comment for "How To Calculate Numbers In String"