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"],
];
asked Jan 15, 2020 at 10:48
DreamTeK
34.6k30 gold badges127 silver badges180 bronze badges
-
I mean, it would certainly be workier since the current code makes no sense.Dave Newton– Dave Newton2020年01月15日 10:50:54 +00:00Commented Jan 15, 2020 at 10:50
2 Answers 2
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);
answered Jan 15, 2020 at 10:49
CertainPerformance
374k55 gold badges354 silver badges359 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
answered Jan 15, 2020 at 11:03
Darshana Pathum
6695 silver badges12 bronze badges
2 Comments
Dave Newton
Why map if you’re just going to use it to iterate?
Darshana Pathum
oops. I saw that. I have't edit the answer before I post. Thank you. I wll update
lang-js