how can i make my function handle multiple string arrays?

Viewed 61

i've been working for some homework in replicating a json parse like function and currently i wrote a function as follows :

var arr = '[a, [a, bjng],  n]'
var intoArray = function(string) {
  if (string.length <= 2) {
    return [];
  }
  var resultsArr = [];
  var toJoin = [];
  var simpArr = string.slice(1, string.length - 1).replace(/['"]+/g, '').replace(/[' '']+/g, '').split(',');
  for (var a = 0; a < simpArr.length; a++) {
    if (simpArr[a].includes('[')) {
      while (!simpArr[a].includes(']')) {
        toJoin.push(simpArr[a]);
        a++;
      }
    }
    if (simpArr[a].includes(']')) {
      toJoin.push(simpArr[a]);
    }
  }
  var joined = toJoin.join(',')
  var joint = joined.slice(1, joined.length - 1).replace(/['"]+/g, '').replace(/[' '']+/g, '').split(',')
  for (var a = 0; a < simpArr.length; a++) {
    if (!toJoin.includes(simpArr[a])) {
      resultsArr.push(simpArr[a])
    }
    if (simpArr[a] === toJoin[0]) {
      resultsArr[a] = joint
    }
  }

  return resultsArr
};

console.log(intoArray(arr))

when run it converts this string '[a, [a, bjng], n]'(this is all just one big string) into [ 'a', [ 'a', 'bjng' ], 'n' ] (this is an array with multiple string and another array inside, this is the desired behavior). However when the sample string has more than one array inside of it like '[a, [a, bjng],[c] , n]' the result is that it is taken as just one bigger array like [ 'a', [ 'a', 'bjng]', '[c' ], 'n' ] (notice how instead of creating two array it thinks that '[a' trough 'c]' is one big array), i'm still learning so some insight would be much appreciated or if someone has some idea of how i can adapt it to handle multiple arrays!!! or perhaps a better implemntation?

2 Answers

Logic is identical to that of my last answer to your similar question here, except it uses chunks of consecutive characters instead of individual characters in order to handle strings longer than 1.

const string = '[a, [a, bjng],  n]'.slice(1, -1);
const chunks = string.match(/\w+|[\[\]|,| ]/g);

const array = [];
let currArr = array;

for (const chunk of chunks) {
  /\w/.test(chunk) && currArr.push(chunk);
  chunk == ']' && (currArr = array);
  if (chunk == '[') {
    currArr = [];
    array.push(currArr);
  }
}

console.log(array); // [ 'a', [ 'a', 'bjng' ], 'n' ]

@GirkovArpa made a good start, but as @Barmar already mentioned: you will need some kind of recursion if you want to process arbitrary (deeper) array structures correctly. Here is my (rudimentary) take on it:

const string = '[a, [ [d,e,[f,g]], bjng], [c], n]';

function parse(str){
  function add2arr(a,p){ var c
    do c=p.shift()
    while( c && (/\w/.test(c)&&a.push(c) 
              || c==','
              || c=='[' &&a.push(add2arr([],p))) );
    return a
  }
  const parts = str.replace(/\s*/g,"").match(/\w+|[\[\],]/g);
  if(parts.shift()=='[') return add2arr([],parts);
}

console.log(parse(string))

// or, much simpler: use JSON.parse:

console.log(JSON.parse(string.replace(/(\w+)/g,'"$1"')));

Related