1

I know I can use split function to transform a string to an array but how can a string be split twice to produce a nested array?

I expected this would be sufficent but it does not produce the desired output.

var myString = "A,B,C,D|1,2,3,4|w,x,y,z|"
var item = myString.split("|");
var array = [item.split(",")];

Would it be more optimal to use a for each loop?

EXPECTED OUTPUT

var array = [
  ["A","B","C","D"],
  ["1","2","3","4"],
  ["w","x","y","z"],
];
1
  • I mean, it would certainly be workier since the current code makes no sense. Commented Jan 15, 2020 at 10:50

2 Answers 2

5

Once you've split on |, use .map to account for the nesting before calling .split again. There's also an empty space after the last |, so to exclude that, filter by Boolean first:

const myString = "A,B,C,D|1,2,3,4|w,x,y,z|";
const arr = myString
  .split('|')
  .filter(Boolean)
  .map(substr => substr.split(','));
console.log(arr);

Or you could use a regular expression to match anything but a |:

const myString = "A,B,C,D|1,2,3,4|w,x,y,z|";
const arr = myString
  .match(/[^|]+/g)
  .map(substr => substr.split(','));
console.log(arr);

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

Comments

1

var myString = "A,B,C,D|1,2,3,4|w,x,y,z"
var item = myString.split("|");

var outputArr = item.map(elem => elem.split(","));
console.log(outputArr);

2 Comments

Why map if you’re just going to use it to iterate?
oops. I saw that. I have't edit the answer before I post. Thank you. I wll update

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.