Home > Software engineering >  Separate numbers from letters and special characters and calculate sum
Separate numbers from letters and special characters and calculate sum

Time:06-06

I want to remove special characters and letters from an array and calculate the sum of the remaining integers in the array, in JavaScript.

const arr = ["13,d42", "d44f2", "1g5", "1c42"];

            let numbersOnly = (val) => {
                if (typeof val === "number") {
                    // replace number with string to get only string values in an array.
                    return val;
                } else {
                    let temp = val.split("");
                    // document.write(temp);
                    let newArr = [];
                    for (let i = 0; i < temp.length; i  ) {
                        if (typeof temp[i].parseInt() === 'number') {
                            document.write(i)
                            newArr.push(temp[i]);
                        }
                    }
                    // return newArr;
                    // document.write(newArr)
                }
            };

            let numbers = arr.map(numbersOnly).reduce((partialSum, a) => partialSum   a, 0);
            document.write(numbers);

CodePudding user response:

reduce over the array. For each string find the numbers using match with a simple regular expression, then join that array into one string, and then coerce it to a number.

const arr = ['13,d42', 'd44f2', '1g5', '1c42'];

const sum = arr.reduce((sum, str) => {
  const num = Number(str.match(/\d/g).join(''));
  return sum   num;
}, 0);

console.log(sum);

Sidenote: you probably shouldn't be using document.write:

⚠ Warning: Use of the document.write() method is strongly discouraged.

CodePudding user response:

Can this help you?

const arr = ["13,d42", "d44f2", "1g5", "1c42"];
const onlyNumbers = arr
    .map((value) => value.replace(/[^0-9]/g, "")) // get just numbers
    .reduce((pv, cv) => parseInt(pv)   parseInt(cv)); // add up the numbers
console.log(onlyNumbers);

CodePudding user response:

I have created getNumber which accepts a string as parameter and return the number which its contain.

For example if we pass "13,d42" so it will gonna return us 1342 as number.

And my another function getTotalSum will call the function for all the string and do some of all numbers which getNumber return;

const arr = ["13,d42", "d44f2", "1g5", "1c42"];

const getNumber = (numberString) => {
let numberRes = '';
for(let i = 0; i< numberString.length;i  ){
    if(!isNaN(parseFloat(numberString[i]))){
        numberRes  = numberString[i]; 
    }
}
return parseFloat(numberRes);
}

const getTotalSum = (arr) => {
let sum = 0;
arr.forEach(el =>{
sum  = getNumber(el)
});
return sum;}

CodePudding user response:

The solution is quite simple if you only want to parse each individual string in the array.

const arr = ["13,d42", "d44f2", "1g5", "1c42"];

const numbersOnly = (val) => {
  const re = /\D/g;
  return parseInt(val.replaceAll(re, ""));
}

let numbers = arr.map(numbersOnly).reduce((partialSum, a) => partialSum   a, 0);
console.log(numbers);

But more importantly what answer are you desiring? Are you treating "13,d42" as 13,42 or 1342?

CodePudding user response:

Use Array#map with a regular expression to replace all special characters and letters then use to convert from string to numeric. Finally, use Array#reduce to add the numbers to get the sum.

const arr = ["13,d42", "d44f2", "1g5", "1c42"],

      output = arr
      .map(item =>  item.replace(/[^\d] /g,''))
      .reduce(
          (sum,item) => sum   item,0
      );
      
console.log( output );

Alternatively ...

You can do it without Array#map as follows:

const arr = ["13,d42", "d44f2", "1g5", "1c42"],

      output = arr
      .reduce(
          (sum,item) => sum    item.replace(/[^\d] /g,''),0
      );
      
console.log( output );

CodePudding user response:

1941 is correct answere. because "13,d42" is first element of the array. returns 1342

const arr = ["13,d42", "d44f2", "1g5", "1c42"];

console.log(arr.map(a =>  a.match(/\d /g).join('')).reduce((a, b) => a   b, 0));  // 1941 => the sum of [ 1342, 442, 15, 142 ]

CodePudding user response:

// Fn to remove numeric part from input string
const stripNonNumeric=(str)=>{return str.replace(/\D/g,'');}

let input =  ["13,d42", "d44f2", "1g5", "1c42"];
// Convert array to numeric array
let numericArray=input.map(item=>(Number(stripNonNumeric(item))))
// Sum array elements
const sum = numericArray.reduce((partialSum, a) => partialSum   a, 0);    
console.log(sum);

  • Related