convert an array of strings to numbers

How to Convert an Array of Strings to Numbers

Converting an array of strings to numbers is a common task in programming. Fortunately, it is a straightforward process in most programming languages. In this post, I will explain how to do it in JavaScript.

Method 1: Using a For Loop

One way to convert an array of strings to numbers is by using a for loop. Here is the code:


const stringArray = ['1', '2', '3', '4', '5'];
const numberArray = [];

for (let i = 0; i < stringArray.length; i++) {
  numberArray.push(parseInt(stringArray[i]));
}

console.log(numberArray); // [1, 2, 3, 4, 5]

In this code, we first create an array of strings called stringArray. We also create an empty array called numberArray that we will use to store the converted numbers.

Next, we use a for loop to iterate over each element in stringArray. For each element, we use the parseInt() function to convert the string to a number and push it into numberArray.

Finally, we log numberArray to the console to verify that the conversion worked.

Method 2: Using Array.map()

Another way to convert an array of strings to numbers is by using the Array.map() method. Here is the code:


const stringArray = ['1', '2', '3', '4', '5'];

const numberArray = stringArray.map(function(element) {
  return parseInt(element);
});

console.log(numberArray); // [1, 2, 3, 4, 5]

In this code, we use the Array.map() method to create a new array called numberArray that contains the converted numbers.

The Array.map() method takes a function as an argument. This function is called for each element in the array and returns a new value. In this case, we use the parseInt() function to convert each string to a number.

Finally, we log numberArray to the console to verify that the conversion worked.

Conclusion

In this post, we learned two ways to convert an array of strings to numbers in JavaScript. The first method uses a for loop to iterate over each element in the array and convert it to a number. The second method uses the Array.map() method to create a new array with the converted numbers.

Both methods are simple and easy to understand, but depending on the context of your program, one method may be more appropriate than the other.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe