ncox85 ncox85 - 7 months ago 22
Javascript Question

Split an array of strings into two arrays, each with a part of the original string

I am working with JSON data, and one of the items I want to use is actually two pieces of information formatted together, separated by |.

This is an example of the string that is being returned: "Rocket | Mission".

I have pulled this information into an array for each rocket | mission, so their are 30 items in the array

I have a for loop that generates this array:

var names = ["rocket1 | mission1", "rocket2 | mission2", ...];

I am trying to separate the items in that array into:

var rocket = ["rocket1, rocket2, rocket3, ...];
var mission = ["mission1, mission2, mission3, ...];

so that I can loop through and display each rocket and mission separately.

I have tried using
substring(indexOf(" | ") +1);
but I keep getting to a point where I need a loop within a loop within a loop. I am a beginner at javascript and I don't understand the syntax and logic well enough to figure out how and where to apply those methods to get what I want.

Hope this makes sense Thanks for your help!


Like squint said in the comments, you're going to want to create the two arrays and then loop through the original array, splitting it into the two new arrays

var rocket = [];
var mission = [];

for (var i = 0; i < names.length; i++) {
    var temp = names[i].split(" | ");