Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Eric Vandenberg
9,095 PointsBasic JavaScript function
Okay so I am trying to separate the two words within the same string using a function. Here is my code...
var carArray = ["Jeep Wrangler", "Toyota Land Cruiser", "Land Rover Range Rover"];
function makeModel(carArray) {
return ????????????????????????;
}
I want to return the input array by breaking up the first string into individual words. So instead of "Jeep Wrangler" it would return "Jeep" and "Wrangler"
If you have any suggestions please help, thanks!!
4 Answers
Aaron Graham
18,033 PointsYou have a real tricky problem on your hands. Using the split method, as mentioned before, will only work for make/model pairs that are represented by single words (i.e. "jeep", "wrangle"). When you get to "Land Rover", "Range Rover", for example, the split method quickly presents a problem. You will end up with an array like this: ['Land', 'Rover', 'Range', 'Rover']. The biggest problem is that you don't have any defined number of array elements that describe the make section and a defined number of elements that define the model section. You will probably need to implement some type of hash table that defines the possible makes of cars: ["Jeep", "Toyota", "Land Rover"], and split the string based on that. Maybe doing something like:
function makeModel(car) {
var models = new Array('Jeep', 'Toyota', 'Land Rover');
returnObj = {};
models.forEach(function(element) {
if (car.indexOf(element) === 0) {
returnObj = {
make: element,
model: car.slice(element.length)
}
};
});
return returnObj;
};
This could probably be refined quite a bit, but hopefully it will give you some direction.
Andrew Molloy
37,259 PointsYou probably want the split method. So iterate your array with car.split(" "), use a for or foreach to loop through the array.
Kinan B
19,428 Pointsif you use the split methode you'll get the two seperate words in an array. I don't know if that's what you meant. type the model's index as an argument for the makeModel function :)
var carArray = ["Jeep Wrangler", "Toyota Land Cruiser", "Land Rover Range Rover"];
function makeModel (idx){
var model = carArray[idx].split(" ");
return model;
}
Eric Vandenberg
9,095 PointsThank you all for your help!! I think I've got it now