I've got two arrays: hobbieList and hobbieTypes. I want to separate the elements in hobbieList, depending on what's the value of their index, in the hobbieTypes array. Something like this:
hobbieList = ["Rock", "Pop", "Surf", "Blues", "Soccer"];
hobbieTypes= ["music", "music", "sport", "music", "sport"];
... so the typical apporach with imperative programming and using fors, would be:
let musicHobbies = [];
for(let i=0;i<hobbieList.length;i++){
if(hobbieTypes[i] === "music"){
musicHobbies.push(hobbieList[i]);
}
}
// Now "musicHobbies" has only the hobbies which type is "music".
But I want to do this with functional programming, using the map() function, and trying to keep the code as short and efficient as possible. Something like this:
let musicHobbies =
hobbieList.map( (elem, ind) => (hobbieTypes[ind] === "music") ? elem : null;
I think it looks nice, but there is a problem: the null positions are not erased, so the array shows a "null" where the condition is not satisfied.
The second apporach I could get into, which works nicely but I don't know if it's the proper way to code in a functional way, is this:
let musicHobbies = [];
rawHobbies.map( (elem, ind) => (hobbiesTypes[ind] === "music") ? musicHobbies.push(elem) : elem);
Is this second solution, well designed? Or should I change something? And also, should I use the array that the map() function returns (as in case 1), or is it ok if I just get my result in an external array (like in case 2)?
Thank you for your help!
EDIT:
What about this other approach?
rawHobbies.map( (elem, ind) => {
switch(hobbiesTypes[ind]){
case "music": this.hobbies.music.push(elem); break;
case "plan": this.hobbies.plans.push(elem); break;
case "hobbie": this.hobbies.hobbies.push(elem); break;
}
});
I guess I'd do this better with forEach. Do you think I should use this, use this with forEach, or do something like this...?
this.hobbies.music = rawHobbies.filter( (x,i) => hobbieTypes[i] == "music");
this.hobbies.plans = rawHobbies.filter( (x,i) => hobbieTypes[i] == "plan");
this.hobbies.hobbies = rawHobbies.filter( (x,i) => hobbieTypes[i] == "hobbie");
I'm not pretty sure which one of these options would work the best. Opinions?
EDIT 2:
I ended up using imperative programming for perfomance purposes, but thank you all for the different approaches I can use with functional programming. My final solution is just a simple foor loop:
for(let i=0;i<rawHobbies.length;i++){
switch(hobbiesTypes[i]){
case "music": this.hobbies.music.push(rawHobbies[i]); break;
case "plan": this.hobbies.plans.push(rawHobbies[i]); break;
case "hobbie": this.hobbies.hobbies.push(rawHobbies[i]); break;
}
}