Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function for the sum of all even numbers

Tags:

javascript

I wanted to create a function which take a string of any numbers and characters as a one parameter. the task is to find all the even numbers(digits) and sum them up then display the total value in console. for example, if the following string is passed to this function as a one parameter ("112,sf34,4)-k)") the result should be : The sum of all even numbers: 10

So far I have come with solution and solve after this. Help me. Thanks in advance.

function functionFive(str) {
    const string = [...str].map(char => {
        const numberString = char.match(/^\d+$/)
        if (numberString !== null){
            const number = parseInt(numberString)
            return number
        }

    const num = string.map(number=>{
        if (number !== undefined && number%2 === 0){
             console.log(number)
        }
    })
}
functionFive("sau213e89q8e7ey1")
like image 220
Gurkiran Singh Avatar asked Jun 03 '20 05:06

Gurkiran Singh


4 Answers

Would this help?

function sumEven(s) {
  return s.split('').map(x=>+x).filter(x=>x%2==0).reduce((a,b)=>a+b)
}

console.log(sumEven('idsv366f4386523ec64qe35c'))
like image 198
djcaesar9114 Avatar answered Oct 13 '22 01:10

djcaesar9114


The below code help you with minimum loops

function sumEven(s) {
  return s
    .split("")
    .filter(x => x % 2 === 0)
    .reduce((acc, val) => acc + Number(val), 0);
}

console.log(sumEven("112,sf34,4)-k)"));
like image 41
Vipin Yadav Avatar answered Oct 13 '22 01:10

Vipin Yadav


I'd just search for all even single digit numbers with the exception of zero (because it will not contribute to the sum) with a regex and sum the resulting array, ie

const functionFive = str => (str.match(/2|4|6|8/g) || [])
  .reduce((sum, num) => sum + parseInt(num, 10), 0)

console.info(functionFive("sau213e89q8e7ey1"))
like image 37
Phil Avatar answered Oct 13 '22 01:10

Phil


Try this:

   function functionFive(str){
     return  str.split('')
            .filter((el)=> !isNaN(el) && el % 2 === 0)
            .reduce((acc,cur)=> parseInt(acc) + parseInt(cur));
          }
       console.log(functionFive("112,sf34,4)-k"))
like image 33
shshsi Avatar answered Oct 12 '22 23:10

shshsi