0
let datas = "1,5,8,4,6"

I want to convert this datas into an array. I use split operator like,

datas.split(",")

But the value is in string type Iwant it in integer format. Like,

 datas=[1,5,8,4,6]

How to covert elements into integer

Lex V
  • 1,414
  • 4
  • 17
  • 35

3 Answers3

3

You can use the map function which creates a new array populated with the results of calling a provided function on every element in the calling array. Read more about map at here.

The number method (Read about it at here) converts a value to a number.

const datas = "1,5,8,4,6";
const arr = datas.split(",").map(d => Number(d));
console.log(arr);

Also as suggested by user @bogdanoff, map(d => +d) can also be used to convert a string value to number.

const datas = "1,5,8,4,6";
const arr = datas.split(",").map(d => +d);
console.log(arr);
user1672994
  • 10,509
  • 1
  • 19
  • 32
1

Works like charm

let datas = "1,5,8,4,6"
console.log(datas.split(",").map(elem => Number(elem)))
JeanJacquesGourdin
  • 1,496
  • 5
  • 25
0

This should work

let datas = "1,5,8,4,6"
datas.split(",")

for (let i=0; i<datas.length; i++){
datas[i] = Number(datas[i])
}
Lord Bee
  • 132
  • 6