0

I have data as follow:

let str = "1,2,3,4"

and, I want to transform it into

arr = [1,2,3,4]
Hemant Singh
  • 99
  • 1
  • 4

3 Answers3

1

You can use split() and Number()

let str = "1,2,3,4";

const output = str.split(',').map(Number);

console.log(output);
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
1

let str = "1,2,3,4"
const nums = str.split(',').map( num => parseInt(num) );

console.log(nums)

You have to split by comma , then you can map through the array of strings and parseInt() them one by one

Kevin.a
  • 4,094
  • 8
  • 46
  • 82
0

actually what you can use is split + map in order to create an array with the values, because they would be strings, you can use + operator to cast it to a number.

like this:

let str = "1,2,3,4"
let newArray = str.split(',').map(n=> +n);
console.log(newArray);
Prince Hernandez
  • 3,623
  • 1
  • 10
  • 19