Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

replace numeric string to number inside an array

I want to convert an array from

arr = ["step","0","instruction","1"]

to

newArr = ["step",0,"instruction",1]

here is my sample code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  newArr = arr.map((x) => {
      if (typeof x === "number") {
        return x;
      }
    });

>Solution :

You could check if the string is convertable to a finite number and map the number in this case.

const
    data = ["step", "0", "instruction", "1"],
    result = data.map(v => isFinite(v) ? +v : v);

console.log(result);

If you need all other numbers as well, you could convert to number and check the the string of is against the value.

const
    data = ["step", "0", "instruction", "1", "NaN", "Infinity"],
    result = data.map(v => v === (+v).toString() ? +v : v);

console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading