1

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;
      }
    });
Emre Savul
  • 55
  • 4
  • 1
    If you're not using the return value of `.map()` then `.map()` is the wrong tool. – Andreas Mar 14 '22 at 09:19
  • What have you tried so far to solve this on your own? You should be able to find suitable solutions with your preferred search provider. – Andreas Mar 14 '22 at 09:20

3 Answers3

2

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • And this is the first time someone asks such a question? Convert some "numbers" in an array into actual numbers? – Andreas Mar 14 '22 at 09:30
  • Nope, see this post here: https://stackoverflow.com/questions/1133770/how-to-convert-a-string-to-an-integer-in-javascript . In That post however they don't account for the fact that not each value in the array is a number. – Flashtube Mar 14 '22 at 09:32
  • the problem is not the conversion, but the check if it is possible. – Nina Scholz Mar 14 '22 at 09:40
0

I think you are looking for something like this:

// Defining initial values
const initialValues = ["step","0","instruction","1"]

// Mapping initial values to a new parsed array
const parsedValues = initialValues.map(value => {
  // We try to parse the value. If it isNaN (Not a number) we just return the value e.g. don't change it
  if(isNaN(parseInt(value))) return value;
  // Else the value can be parsed to a number, so we return the parsed version.
  return parseInt(value);
})
// Printing the parsed results
console.log(parsedValues);
Flashtube
  • 209
  • 1
  • 6
0

try this:

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

const newArray = arr.map(value => { //Iterate the array searching for possible numbers.
/* Check with function isNaN if the value is a number, 
  if true just return the value converted to number, 
  otherwise just return the value without modification */
  if (!Number.isNaN(Number(value))) { 
      return Number(value)
  }

  return value
})
narF
  • 70
  • 4