What’s Up with this function? I cant get it to create a new array?
function sumDigitsFromString (str) {
str=str.split('');
console.log(str)
var arr1= [];
function listNumber (x)
{
if(typeof x == 'number')
{
console.log(x)
arr1.push(x);
}
}
str.forEach(listNumber);
console.log(arr1);
}
sumDigitsFromString('12334')
Your if statement will not execute
if(typeof x == 'number')
{
console.log(x)
arr1.push(x);
}
because each value’s type is not a number. They are strings.
[ '1', '2', '3', '3', '4' ]
. You will need to convert them to numbers to make it work. One way to do is using a built in method like Number().
Because you have split str into an array of little strings (single characters) typeof x will never be number
How do I get it so that It filters out NaN
function sumDigitsFromString (str) {
str=str.split('');
console.log(str)
var arr1= [];
function listNumber (x)
{
x = Number(x)
if(typeof x === 'number' && x !== NaN)
{
console.log(x)
arr1.push(x);
}
}
str.forEach(listNumber);
console.log(arr1);
}
sumDigitsFromString("12j34")
I think you can use isNaN method, i added a MDN link
Yeeet
function sumDigitsFromString (str) {
str=str.split('');
console.log(str)
var arr1= [];
function listNumber (x)
{
x = Number(x)
if(typeof x === 'number' && !isNaN(x))
{
console.log(x)
arr1.push(x);
}
}
function sumOf (total, number1)
{
return total+number1
}
str.forEach(listNumber);
console.log(arr1);
console.log(arr1.reduce(sumOf))
}
sumDigitsFromString("12j34")