Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert all elements in an array to integer in JavaScript?

Tags:

javascript

I am getting an array after some manipulation. I need to convert all array values as integers.

My sample code

var result_string = 'a,b,c,d|1,2,3,4'; result = result_string.split("|"); alpha = result[0]; count = result[1]; // console.log(alpha); // console.log(count); count_array = count.split(","); 

count_array now contains 1,2,3,4 but I need these value to be in integers.

I had used parseInt(count_array);, but it fails. JS considers each value in this array as string.

like image 867
Mohan Ram Avatar asked Dec 14 '10 09:12

Mohan Ram


People also ask

How do I convert an element to an array to int?

You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them.

How do I turn an array into a number?

To convert an array of strings to an array of numbers, call the map() method on the array, and on each iteration, convert the string to a number. The map method will return a new array containing only numbers. Copied!

How do you convert an array of integers into a single integer in Java?

We can use the parseInt() method and valueOf() method to convert char array to int in Java. The parseInt() method takes a String object which is returned by the valueOf() method, and returns an integer value. This method belongs to the Integer class so that it can be used for conversion into an integer.

How do you convert a number to an integer in JavaScript?

In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.


1 Answers

ECMAScript5 provides a map method for Arrays, applying a function to all elements of an array. Here is an example:

var a = ['1','2','3'] var result = a.map(function (x) {    return parseInt(x, 10);  });  console.log(result);

See Array.prototype.map()

like image 84
dheerosaur Avatar answered Sep 22 '22 03:09

dheerosaur