I have a string that contains a mix of characters and numbers. I want to separate out the numbers from the string and store them in an Array. So far I have been able to separate the strings and numbers and put them in Array and then able to get only numbers but the string type data is NaN. I am unable to get rid of NaN values from the Array.
So far my code looks like this:
arrayList = "abcd_456_yasdb_382_h_83_2";
new_arrayList = arrayList.split('_');
console.log(new_arrayList); // Output : [ 'abcd', '456', 'yasdb', '382', 'h', '83', '2' ]
new_arrayList = new_arrayList.map(Number);
console.log(new_arrayList); // Output : [ NaN, 456, NaN, 382, NaN, 83, 2 ]
onlyNumArray = []
for(i =0; i<new_arrayList.length; i++) {
// console.log(new_arrayList[i]);
if(typeof (new_arrayList[i]) === "number" && typeof(new_arrayList[i]) != NaN) {
onlyNumArray.push(new_arrayList[i])
}
else {
console.log("Not a number")
}
}
console.log(onlyNumArray) // Output : [ NaN, 456, NaN, 382, NaN, 83, 2 ]
Output = [ NaN, 456, NaN, 382, NaN, 83, 2 ]
Expected Output = [456, 382,83,2]
typeof NaNreturns 'number', so you'll want to replace that condition with!isNaN(new_arrayList[i])