0

I am getting a set of arrays in string format which looks like

[49,16,135],[51,16,140],[50,18,150]

Now I need to save them in an array of arrays. I tried it like

let array = [];
let str = '[49,16,135],[51,16,140],[50,18,150]';
array = str.split('[]');
    
console.log(array);

but it is creating only one array including all string as an element while I need to have

array = [[49,16,135],[51,16,140],[50,18,150]]
1
  • It's returning one string because the substring [] does not appear in the str Commented Feb 9, 2019 at 6:21

3 Answers 3

4

Add array delimiters to each end of the string, then use JSON.parse:

const str = '[49,16,135],[51,16,140],[50,18,150]';
const json = '[' + str + ']';
const array = JSON.parse(json);
console.log(array);

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

1 Comment

you were faster! :D
2

You are splitting it incorrectly, in the example, it will only split of there is a [] in the string

You can create a valid JSON syntax and parse it instead like so,

let str = '[49,16,135],[51,16,140],[50,18,150]';
let array = JSON.parse(`[${str}]`);

console.log(array);

1 Comment

Yeah @Taplar I copied the snippet from question for faster response, Will edit.
0

Another way you could achieve this is by using a Function constructor. This method allows you to "loosely" pass your array.

const strArr = "[49,16,135],[51,16,140],[50,18,150]",
arr = Function(`return [${strArr}]`)();

console.log(arr);

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.