最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - function for the sum of all even numbers - Stack Overflow

programmeradmin3浏览0评论

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

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")
Share Improve this question asked Jun 3, 2020 at 5:53 Gurkiran SinghGurkiran Singh 3195 silver badges14 bronze badges 2
  • 2 Are you talking just single digit numbers? Ie 112 is 1, 1 and 2 – Phil Commented Jun 3, 2020 at 5:57
  • 1 Your function doesn't return anything. On top of that, you have unmatched brackets. – Gerardo Furtado Commented Jun 3, 2020 at 5:57
Add a comment  | 

7 Answers 7

Reset to default 9

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

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

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

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)

发布评论

评论列表(0)

  1. 暂无评论