0

I have an array: var array = ['1,2,3']

How do i remove the: ' from that array so i get the output [1,2,3]

I have tried doing the .replace replace("\''", "") but still get the same output.

Brad
  • 159
  • 11
  • Possible duplicate of [Convert string containing arrays to actual arrays](https://stackoverflow.com/questions/29191171/convert-string-containing-arrays-to-actual-arrays) – Heretic Monkey Feb 25 '18 at 16:05

2 Answers2

1

You can use map on array and then split on value.

var array = ['1,2,3']
array = [].concat(...array.map(e => e.split(',').map(Number)))
console.log(array)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

For the specific case you’ve given, with just one string item in the array, it can be boiled down to:

var array = ['1,2,3']
var result = array[0].split(',').map(x => +x)
//                 ^  ^          ^   ^^^^ ^
//                 1  2          3   4    5

console.log(result)
  1. Take the first (and only) element in the array
  2. split the string wherever there’s a comma
  3. Use map to apply a function (point 4) to each element that split() returns
  4. An arrow function that takes a parameter x and...
  5. Coerces x into a number with the + operator

If you might have many string items in your array, like:

var array = [‘1,2,3’, ‘4,5,6’]

then Nenad’s answer’s great.

Clarence Lee
  • 141
  • 6