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?

slindsey3000
  • 4,053
  • 5
  • 36
  • 56

4 Answers4

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));
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
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']];
zachzurn
  • 2,161
  • 14
  • 26
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/.

v7d8dpo4
  • 1,399
  • 8
  • 9
0
var array = JSON.parse("[" + str + "]");

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

Istiak Morsalin
  • 10,621
  • 9
  • 33
  • 65