1

I want to split a string of Arrays into an actual array in Javascript(react).

Original String :

[" 103.116.32.2",1225],[" 163.53.79.51",677],[" 103.116.32.30",651],[" 103.116.32.1",174],[" 10.6.27.6",40],[" 184.26.162.104",36],[" 184.26.162.97",35],[" 10.57.10.88",27],[" 172.16.59.56",24],[" 8.8.4.4",22],[" 103.116.32.26",18],[" 8.8.8.8",17],[" 103.116.32.14",16],[" 192.168.180.5",14],[" 216.239.35.0",10],[" 10.6.24.135",9]

Result I want : nested array with these values

newArray = [
[" 103.116.32.2",1225], 
[" 163.53.79.51",677], 
[" 103.116.32.30",651] ...etc
];

What I have tried:

I have tried string.split(",") but this doesnt work because there is a comma inbetween the inner arrays. So the results gives newArray = [[" 103.116.32.2"] , [1225] , [" 163.53.79.51"] , [677]]

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
utpalbalse
  • 11
  • 2

1 Answers1

5

Your source string is pretty close to valid JSON, you just need to wrap it in [] to be able to parse it:

const source = '[" 103.116.32.2",1225],[" 163.53.79.51",677],[" 103.116.32.30",651],[" 103.116.32.1",174],[" 10.6.27.6",40],[" 184.26.162.104",36],[" 184.26.162.97",35],[" 10.57.10.88",27],[" 172.16.59.56",24],[" 8.8.4.4",22],[" 103.116.32.26",18],[" 8.8.8.8",17],[" 103.116.32.14",16],[" 192.168.180.5",14],[" 216.239.35.0",10],[" 10.6.24.135",9]';

const result = JSON.parse(`[${source}]`);

console.log(result);
Cerbrus
  • 70,800
  • 18
  • 132
  • 147