How to convert a string representation to an array integers?

Viewed 127

How to convert a single string element representing an array of integers as strings to an array of integers in Javascript?

I have a string like this

var str = "["163600", "163601", "166881"]";

My output should be

[163600, 163601, 166881]

What I am trying is

var myArr = JSON.parse(str)

but in result I am getting an array of strings.

["163600", "163601", "166881"]

How can I get an array of integers?

I am trying to further parse like this

parseInt(myArr) but this is giving only for 0th index. Is there any way to get for the whole array?

4 Answers

The easy way is using .map() to create a new array along with using Number to parse each string into numbers.

var str = ["163600", "163601", "166881"];
var result = str.map(Number);
console.log(result);

/*Using `JSON.parse` first if your data is not an string array.*/
console.log(JSON.parse("[\"163600\", \"163601\", \"166881\"]").map(Number));


More detailed explanation

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

When used as a function, Number(value) converts a string or other value to the Number type. If the value can't be converted, it returns NaN.

Try using map:

var string = "[\"163600\", \"163601\", \"166881\"]";
var result = JSON.parse(string).map(function(number){ return parseInt(number, 10) || number; });

console.log(result);

const result = strings.map(el => parseInt(el));

Number function will work too. Don't include curly braces in the callback.

Use + operator to convert to Number

var str = "[\"163600\", \"163601\", \"166881\"]";

const res = JSON.parse(str).map(item => +item);

console.log(res)

Related