js how to convert all string in array into integer

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:

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:

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:

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:

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.

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