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]]

3
  • so JSON.parse it Commented Jun 20, 2022 at 13:59
  • What you are showing as your "original string" isn't a string. There's also no such thing as a "string of arrays". Please clarify. Commented Jun 20, 2022 at 13:59
  • 1
    Modify whatever is giving you this string to give you a JSON string instead. Commented Jun 20, 2022 at 14:54

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.