-6

I am getting below line in my source file and I would like to sum those values separated by pipe ("|")

There is no limit for the values coming in the line (might be 100 values)

10|20|30|40|[no limit for values] - Separator is pipe "|" 

The ouptput would be 100

Please help to write a javascript function for the above query.

Regards Jay

Thalaivar
  • 23,282
  • 5
  • 60
  • 71
  • 1
    What have you tried so far? Stack Overflow isn't just a code writing service, you need to show you have attempted something and indicate specifically where you are stuck. – Christopher Moore Aug 09 '17 at 11:34
  • Use `string.split()` to split the string into an array. Use `parseInt()` to convert those strings into numbers. And use `array.reduce()` to add them up. – Barmar Aug 09 '17 at 11:35
  • 2
    close duplicate of https://stackoverflow.com/q/1230233/104380 – vsync Aug 09 '17 at 11:35

2 Answers2

2

You should take a look at JavaScript's built-in functions: With split you can split your string into an array, with reduce you can 'reduce' your array to a single value, in that case via summation. These two links should provide you enough information for building your code.

Stephan
  • 2,028
  • 16
  • 19
0

You could try something like below:

function sum(value){
  var total = 0;
  var array = value.split(",").map(Number);
  for( var i = 0; i < array.length; i++) {
     total += array[i];
  }
  alert(total);
}
var value = "10|20|30|40".replace(/\|/g, ',');

console.log(sum(value));

https://jsfiddle.net/f7uqw7cL/

Thalaivar
  • 23,282
  • 5
  • 60
  • 71