0

Is there by any chance a built-in javascript function that parses:

var string = '[2,1,-4]';
var multiString = '[[-3,2,-1][2,-3,2][1,-1,3]]';

to

var array = [2,1,-4];
var multiArray = [[-3,2,-1],[2,-3,2],[1,-1,3]];

or do I have to write a custom function for this?

4
  • 2
    You have a syntax error in your resulting multiarray. Commented May 1, 2014 at 13:24
  • 1
    How did you end up with strings and not Arrays? Commented May 1, 2014 at 13:24
  • 1
    That could almost be valid JSON, but is not... Commented May 1, 2014 at 13:24
  • @putvande read from file Commented May 1, 2014 at 13:28

3 Answers 3

2

Assuming your correct your multiString to the correct format
(ie. '[[-3,2,-1],[2,-3,2],[1,-1,3]]')

Then yes.

array = JSON.parse(string);
multiArray = JSON.parse(multiString);
Sign up to request clarification or add additional context in comments.

2 Comments

So if I can change a bit the initial string format is possible.. hmm Thanks!
He can do JSON.parse(multiString.replace(/\]\[/g,"],[")); if necessary
0

For completeness, you can use eval:

var s = '[1,2,3]';
var a = eval(s);

however if the string is valid JSON, then as Niet suggested, JSON.parse is a much better solution.

Comments

0

If you want to do this on your own, it can be done using substring and split. A possible solution could look like this:

var multiString = '[[-3,2,-1][2,-3,2][1,-1,3]]';
var string = '[2,1,-4]';    
function parse(input) {
    var s = input;
    // remove leading [ and trailing ] if present
    if (input[0] == "[") {
        s = input.substring(0, input.length);
    }
    if (input[input.length] == "]") {
        s = s.substring(input.length-1, 1);
    }
    // create an arrray, splitting on every ,
    var items = s.split(",");
    return items;
}
// items is now an array holding 2,-1,4
var items = parse(string);

You can then split the bigger string into smaller chunks and apply the function to each part using array.map:

function parseAOfA(input) {
    var s = input.substring(0, input.length).substring(input.length-1, 1);
    s = s.substring(0, s.length).substring(s.length-1, 1);
    s = s.split("][");
    var items = s.map(parse);
    return items;
}
var items = parseAOfA(multiString);

4 Comments

This doesn't work for the multiString '[[-3,2,-1],[2,-3,2],[1,-1,3]]'
I am extending my answer right now to address this part of the question too.
Yes, that's the "hard" way to go. I was going to come to this if something like JSON.parse() wouldn't work. Thanks for your time - downvote neutralised.
@putvande i have updated my code, so my solution now works for both inputs.

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.