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")
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)"));
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"))
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With