I am trying to have my forEach loop loop through var fruit and push any found strings into arr2.
Here is my code:
var fruit = [1,2,3, "apple", "banana", "grape"]
function isString(fruit) {
var arr2 = []
fruit.forEach(function(element) {
if(element == "string"){
arr2.push(element)
}
return arr2
})
}
//desired output is arr2 = "apple", "banana", "grape"
I'm not sure what I'm doing wrong here. Thanks for any advice.
typeof(developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…) to get the type:if (typeof element === "string")if(typeof element == "string"){. Right now you are checking if1 == "string",2 == "string",3 == "string","banana" == "string"so on.. which will befalse. You are basically wanted to check their type, not the value.