Home > database >  Convert elements in an array into integer type
Convert elements in an array into integer type

Time:07-12

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

CodePudding user response:

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);

CodePudding user response:

Works like charm

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

CodePudding user response:

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])
}
  • Related