function for the sum of all even numbers

Viewed 812

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")
7 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'))

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"))

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)"));

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"))

My suggestion:


function isNumber(char) {
  return parseInt(char) !== 'NaN';
}

function functionFive(str) {
   // 1. split str into array
   const charList = str.split('');

   // 2. filter out non-numbers
   const numberList = str.filter(isNumber);

   // 3. return the sum of the numbers using reduce
   return numberList.reduce((acc, curr) => curr % 2 === 0 ? acc + curr : acc, 0);
}
functionFive("sau213e89q8e7ey1")

Hope it helps and its easy to understand :)

Using Regular expressions

const functionFive = str => (str.match(/\d/g)||[]).reduce((a,b)=>a=parseFloat(a)+(parseFloat(b)%2==0?parseFloat(b):0),0);

console.log(functionFive("112,sf34,4)-k)"))

A one line solution to get the result. Hope this helps

let text = "2543sadadfh7896";
let evenNums = text.match(/\d+/g);
let result = evenNums!== null ? evenNums.join().split('').filter(i => i%2 ===0).reduce((a, b) => Number(a) + Number(b)) : 0;

console.log(result)

Related