Ihave to write a function that takes an array as an argument and extracts all the strings of the array and puts them into a new array:
//====================== EXAMPLE ========================
isString([3,55,66,"hello"])
["hello"] // <====== EXPECTED OUTPUT
isString([3,55,66,"hello","beer",12,{},[],()=>{},"[]"])
["hello","beer","[]"] // <====== EXPECTED OUTPUT
//=========================================================
I wrote this:
function isString(arr){
if(typeof arr[i] === 'string'){
arr2.push(arr[i]);
}
}
But I get undefined I don’t know why.
Advertisement
Answer
function isString(arr){
var arr2 = [];
arr.forEach(el => {
if(typeof el === 'string'){
arr2.push(el);
}
});
return arr2;
}
console.log(isString([3,55,66,"hello","beer",12,{},[],()=>{},"[]"]))