Home > Software design >  How to remove alphabets from array of string and convert to number
How to remove alphabets from array of string and convert to number

Time:12-19

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(/[a-z-A-Z]/g, "");
var h = f.split(",");
h.filter(n => n)
console.log(h)

CodePudding user response:

you can multiply string by 1 to convert and check if it is number

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));

CodePudding user response:

Convert them to Numbers and remove those that aren't:

nums = fruits.map(Number).filter(x => !Number.isNaN(x))

CodePudding user response:

You can use isNaN function to check if a variable is number or not. Here is the code with simple logic.

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
  • Related