I want to convert an array from
arr = ["step","0","instruction","1"]
to
newArr = ["step",0,"instruction",1]
here is my sample code:
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);