how to change array element to integer in js

How to Change Array Element to Integer in JavaScript

If you're working with JavaScript arrays, you may have encountered a situation where you need to convert an array element to an integer. Here are a few ways to accomplish this:

Method 1: Using parseInt()

The parseInt() function in JavaScript allows you to parse a string and convert it into an integer. You can use this function to convert an array element to an integer:


    const arr = ["1", "2", "3"];
    const intArr = arr.map(elem => parseInt(elem));
    console.log(intArr); // [1, 2, 3]
  

In this example, we have an array of strings. We use the map() function to apply the parseInt() function to each element of the array, which converts the string to an integer.

Method 2: Using the Unary Plus Operator

Another way to convert an array element to an integer is by using the unary plus operator. This operator converts a string to a number:


    const arr = ["1", "2", "3"];
    const intArr = arr.map(elem => +elem);
    console.log(intArr); // [1, 2, 3]
  

In this example, we again use the map() function to apply the unary plus operator to each element of the array, which converts the string to an integer.

Method 3: Using for Loop

If you prefer to use a for loop instead of the map() function, you can also convert an array element to an integer using the parseInt() function:


    const arr = ["1", "2", "3"];
    const intArr = [];
    for (let i = 0; i < arr.length; i++) {
      intArr.push(parseInt(arr[i]));
    }
    console.log(intArr); // [1, 2, 3]
  

In this example, we loop through the array using a for loop and push each converted integer into a new array.

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