[英]How to remove alphabets from array of string and convert to number
can someone help me, I need to remove alphabets from array of strings and convert it to array of numbers, this is what I did but not getting it right.有人可以帮我吗,我需要从字符串数组中删除字母并将其转换为数字数组,这就是我所做的但没有做对。
const fruits = [" 2", " 1", " 0", "remove this", " 1", " 2", " 0", " 0", " 1", " 0"]; let text = fruits.toString(); var f = text.replace(/[azAZ]/g, ""); var h = f.split(","); h.filter(n => n) console.log(h)
Convert them to Numbers
and remove those that aren't:将它们转换为Numbers
并删除那些不是的:
nums = fruits.map(Number).filter(x => !Number.isNaN(x))
you can multiply string by 1 to convert and check if it is number您可以将字符串乘以 1 进行转换并检查它是否为数字
const fruits = [" 2", " 1", " 0", "remove this", " 1", " 2", " 0", " 0", " 1", " 0"];
console.log(fruits.filter((v)=> !Number.isNaN(v*1)).map((v)=> Number(v) * 1));
You can use isNaN function to check if a variable is number or not.您可以使用 isNaN 函数来检查变量是否为数字。 Here is the code:这是代码:
const fruits = [" 2", " 1", " 0", "remove this", " 1", " 2", " 0", " 0", " 1", " 0"];
var nums=[]; // array for numbers
for( let i = 0; i < fruits.length ;i++){
if(!isNaN(fruits[i])) // check if the value is number or not
nums.push(parseInt(fruits[i]));//add numbers in array with int parsing
}
console.log(nums) //print the array of numbers only
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.