Reputation: 75
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);
and split();
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!
Upvotes: 2
Views: 103
Reputation: 350147
You can use map
together with split
:
var names = ["rocket1 | mission1", "rocket2 | mission2"];
var rockets = names.map( name => name.split(' | ')[0] );
var missions = names.map( name => name.split(' | ')[1] );
console.log(rockets)
console.log(missions);
This uses reduce
and destructuring to accomplish the task in one cycle. Functional programming die-hards may like this one, but it is harder to read for those not accustomed to these compact reduce
constructs.
var names = ["rocket1 | mission1", "rocket2 | mission2"];
var [rockets, missions] = names.reduce( (pairs, name, i) =>
([pairs[0][i], pairs[1][i]] = name.split(' | '), pairs)
, [[], []]);
console.log(rockets);
console.log(missions);
Upvotes: 3
Reputation: 351
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(" | ");
rocket.push(temp[0]);
mission.push(temp[1]);
}
Upvotes: 2
Reputation: 30557
Use split while taking a functional approach with forEach
let names = ["rocket1 | mission1", "rocket2 | mission2"]
let rocket = []
let mission = []
names.forEach(name => {
let splat = name.split(' | ')
rocket.push(splat[0])
mission.push(splat[1])
})
console.log(rocket)
console.log(mission)
Upvotes: 3