Skip to content
Related Articles

Related Articles

Improve Article

How to convert array of strings to array of numbers in JavaScript ?

  • Difficulty Level : Expert
  • Last Updated : 22 Jun, 2021

In this article, we have given an array of strings and the task is to convert it into an array of numbers in JavaScript.

Input: ["1","2","3","4","5"]
Output: [1,2,3,4,5]

Input: ["10","21","3","14","53"]
Output: [10,21,3,14,53]

There are two methods to do this, which are given below:

Method 1: Array traversal and typecasting: In this method, we traverse an array of strings and add it to a new array of numbers by typecasting it to an integer using the parseInt() function.

Javascript




<script>
  
    // Create an array of string
    var stringArray = ["1", "2", "3", "4", "5"];
  
    // Create an empty array of number
    var numberArray = [];
  
    // Store length of array of string
    // in variable length
    length = stringArray.length;
  
    // Iterate through array of string using
    // for loop
    // push all elements of array of string
    // in array of numbers by typecasting
    // them to integers using parseInt function
    for (var i = 0; i < length; i++)
  
        // Instead of parseInt(), Number()
        // can also be used
        numberArray.push(parseInt(stringArray[i]));
  
    // Print the array of numbers
    console.log(numberArray);
</script>

Output:

[1, 2, 3, 4, 5]

Method 2: Using map() method of JavaScript: In this method, we use the array map method of JavaScript.

Javascript




<script>
    // Create an array of string
    var stringArray = ["10", "21", "3", "14", "53"];
  
    // Create a numberArray and using
    // map function iterate over it
    // and push it by typecasting into
    // int using Number
    var numberArray = stringArray.map(Number);
  
    // Print the array of numbers
    console.log(numberArray);
</script>

Output:

[10, 21, 3, 14, 53]



My Personal Notes arrow_drop_up
Recommended Articles
Page :