Skip to content
the poor coder

js how to convert all string in array into integer

Poor Man
Published
Reading time
1 min read

When it comes to converting all strings in an array into integers, there are a few different approaches you can take. The first is to use the built-in parseInt() function. This function takes in a string and an optional radix, and then returns the corresponding parsed integer:

Text
let arr = ["1", "2", "3"];
let intArr = arr.map(str => parseInt(str));
// intArr = [1, 2, 3]

Another approach is to use the Number() constructor. This takes in a string, and returns the corresponding number. It may be preferable to the parseInt() function if you do not need to specify the radix:

Text
let arr = ["1", "2", "3"];
let intArr = arr.map(str => Number(str));
// intArr = [1, 2, 3]

If you need something more flexible that can handle strings as well as numbers, you can also use the Number.parseInt() static method. This takes in a string and an optional radix, and then returns the corresponding parsed integer, or NaN if it could not be parsed:

Text
let arr = ["1", "2", "abc"];
let intArr = arr.map(str => Number.parseInt(str));
// intArr = [1, 2, NaN]

Finally, if you need to handle strings and non-numeric values, you can use the Number.parseInt() static method with a custom callback function. This callback function can check the type of the input, and then return the desired value:

Text
let arr = ["1", "2", "abc"];
let intArr = arr.map(str => {
    if (typeof str === "string") {
        return Number.parseInt(str);
    } else {
        return str;
    }
});
// intArr = [1, 2, "abc"]

Overall, these are just a few of the different approaches you can take to convert all strings in an array into integers. Each can be useful depending on your specific situation, so it's worth exploring them all.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC