1

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)

2
  • What's not correct with your output? Is it the random " " that you have as the 4th element? Would help if you showed your expected output Commented Dec 19, 2022 at 8:12
  • Yes, this is my expected out put: [2, 1, 0, 1, 2, 0, 0, 1, 0] Commented Dec 19, 2022 at 11:50

3 Answers 3

6

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)));
Sign up to request clarification or add additional context in comments.

1 Comment

Number(v) * 1 -> Number(v)
4

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

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

Comments

0

You can use isNaN function to check if a variable is number or not. 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.