1
const str = "[1,2,3,4],5,6";

const getArray = (str) => {
...
return arr;
}

console.log(getArray(str));  //[1,2,3,4]

[1,2,3,4] is the expected array.

How can I get this one?

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Mike
  • 31
  • 1

5 Answers5

1

You can use regex for extracting the numbers enclosed by [] then run a map for sanitize. Check this-

const str = "[1,2,3,4],5,6";

const getArray = str => {
    const regex = /(\[([^\]]+)\])/;
    const match = regex.exec(str);
    
    return match?.[2] ? match[2].split(',').map(x => x.trim()) : [];
}

console.log(getArray(str));
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30
1

This will give you an array of all arrays within your string.

const str = "[1,2,3,4],5,6";

const getArray = (str) => {
  const ans = []
  let stack = []
  let isStack = true
  for (let i = 0; i < str.length; i++) {
    if (str[i] == '[') {
      isStack = true;
    } else if (str[i] == ']') {
      isStack = false;
      ans.push(stack)
      stack = []
    } else if (isStack && str[i] != ',') {
      stack.push(parseInt(str[i]))
    }
  }
  return ans;
}

console.log(getArray(str)) // [ [ 1, 2, 3, 4 ] ]
console.log(getArray(str)[0]) // [ 1, 2, 3, 4 ]
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
alexnik42
  • 188
  • 10
1

You can use the JavaScript method lastIndexOf() to find the [ and ].

This will give you all characters in-between [ and ].

Then you can use the split() method to convert the array.

Using map() and Number you can convert string to number

const str = "[1,2,3,4],5,6";

function getArray(str){
  var myArray = str.substring(
    str.lastIndexOf("[") + 1, 
    str.lastIndexOf("]")
  );
  return myArray.split(",").map(Number);

}

console.log(getArray(str));
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
0

Assuming that str contains exactly one pair of enclosing square brackets:

const getArray = (str) => {
  const idxStart = str.indexOf('[') + 1
  const idxEnd = str.indexOf(']')
  arr = str.slice(idxStart, idxEnd)
  return arr.split(',')

}

DIRECTcut
  • 140
  • 9
0

You can use RegEx to match the string enclosed in []

const str = "[1,2,3,4],5,6";

const getArray = (str) => {
  arr = str.match('/\[.*\]/')[0]
  return arr;
}

console.log(getArray(str));
Not A Bot
  • 2,474
  • 2
  • 16
  • 33