0

I have the following variable with some number.

const string = "5,5,5,5";
const string = "5,5,5,5,10";

I pasted it twice to explain what I am trying to do.

I want to add all the numbers and get a total.

The first I did, is cleaning the variable to avoid the commas, when I split it

let stringWithoutSigns = string.replace(/,/g, "");

I paste the full code to better understanding.

const string = "5,5,5,5";

let stringWithoutSigns = string.replace(/,/g, "");

let itemString = stringWithoutSigns.length;

if (itemString > 2) {
  result = cleanString();
  console.log(result)
}

function cleanString() {
  let arrString = stringWithoutSigns.split("").map(function(index) {
    return parseInt(index, 10);
  });
  console.log(arrString);
  let sum = arrString.reduce(function(a, b) {
    return a + b;
  });
  return sum;
}

My problem, is that if I type a new number like 10, it doesn't works, because is splitted into 1, 0

Barmar
  • 741,623
  • 53
  • 500
  • 612
Sargentogato
  • 85
  • 1
  • 2
  • 9

4 Answers4

1

Don't remove the commas, use them to split the string into numbers.

const string = "5,5,5,5";

result = cleanString(string);
console.log(result)


function cleanString(string) {
  let arrString = string.split(",").map(function(num) {
    return parseInt(num, 10);
  });
  console.log(arrString);
  let sum = arrString.reduce(function(a, b) {
    return a + b;
  });
  return sum;
}
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Split the string by checking , rather that on empty string. Hope this is what you are looking for.

const string = "5,5,5,10";

let stringWithoutSigns = string.replace(/,/g, "");

let itemString = stringWithoutSigns.length;

if (itemString > 2) {
result = cleanString();
console.log(result)
}

function cleanString() {
  let arrString = string.split(",").map(function(index) {
    return parseInt(index, 10);
  });
  console.log(arrString);
  let sum = arrString.reduce(function(a, b) {
    return a + b;
  });
  return sum;
}
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
0

I let one answer more. I can pass an empty string, 0, or as may numbers as I want(I tested it with 20 numbers untill now)

const string = "5,5,5,5,10"

console.log(add(string))

function add(string) {
  let splitted = string.split(",");
  let numbers = splitted.map(value => Number(value || 0));
  return numbers.reduce((a, b) => a + b);
}
Sargentogato
  • 85
  • 1
  • 2
  • 9
0

Basic

string.split(',').reduce((num,acc)=> parseInt(num) + parseInt(acc) )
manish kumar
  • 4,412
  • 4
  • 34
  • 51