1

If I have str = "[[1,Warriors,NBA],[2,Kings,NBA],[3,Knicks,NBA]]" how could I turn that into a array in JavaScript?

An array where each element of the array is an array itself.

Possible?

9
  • Why not just create an array to begin with, or at least valid JSON Commented Mar 21, 2016 at 1:35
  • If this is the content format you're stuck with, then you will have to write your own parser that understands that format. There is no pre-built way to parse this non-standard format. Commented Mar 21, 2016 at 1:38
  • What is source of this string? Making it valid json at source would help Commented Mar 21, 2016 at 1:38
  • It is something that is being passed in as is Commented Mar 21, 2016 at 1:38
  • I think I will explore making it into valid JSON and going from there... thx. Though I am curious if the above can be turned into an actual array. Commented Mar 21, 2016 at 1:40

4 Answers 4

2

You can try this rudimentary function I put together for 2D arrays:

function customParse(data){
    arr = []
    for(var i = 0; i < str.length; i++){
      if(str[i] == ','){
        if(!isNaN(str[i-1])){
          arr.push(',')
          arr.push('"')
        }else{
          if(str[i-1] != "]"){
            arr.push('"')
            arr.push(',')
            arr.push('"')
          }else{
            arr.push(',')
          }
        }
      }else{
        if(str[i] == ']' && str[i-1] != ']'){
          arr.push('"')
        }
        arr.push(str[i])
      }
    }
    return JSON.parse(arr.join(""))
}

str = "[[1,Warriors,NBA],[2,Kings,NBA],[3,Knicks,NBA]]"
result = customParse(str)
alert("Raw: "+result);
alert("Stringified: "+JSON.stringify(result));

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

Comments

2

A little dirty, but will do the trick. the "matches" variable would contain your array of arrays.

var str = "[[1,Warriors,NBA],[2,Kings,NBA],[3,Knicks,NBA]]";
var cleanStr = str.substring(1,str.length-1)

var matches = [];

var pattern = /\[(.*?)\]/g;
var match;

while ((match = pattern.exec(cleanStr)) != null)
{
  matches.push(match[1].split(","));
}

Additionally, if you have the option, just define the array in javascript.

var list = [[1,'Warriors','NBA'],['2','Kings','NBA'],[3,'Knicks','NBA']];

Comments

0

There are some javascript parsers written in javascript. See this:JavaScript parser in JavaScript, this:https://github.com/mishoo/UglifyJS, this:http://esprima.org/, this:http://marijnhaverbeke.nl/acorn/.

1 Comment

This isn't an answer, it should be a comment.
0
var array = JSON.parse("[" + str + "]");

or you can use .split(), that will also end up with an Array of strings.

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.