0

I'm learning javascript and I decided to try out working with methods, constructors and the this keyword. I made a method for finding cars based on certain words that match words inside of property values. If it turns out that a word matches a value, then it returns that object. The problem is, when multiple objects have the same property values, only the first of them is returned. How do I get all of the objects with the same value to return? Can it be solved simply or is the solution really advanced? I tried a ton of variations with the this keyword but nothing worked.

//The constructor
function car(make, model, year, condition){
    this.make = make;
    this.model = model;
    this.year = year;
    this.condition = condition;
}

//An object that holds properties that are really just more objects
var cars = {
car1: new car("Toyota", "Corolla", 2013, "New"),
car2: new car("Hyundai", "Sonata", 2012, "Used"),
car3: new car("Honda", "Civic", 2011, "Used") 
};

//The method
findCar = function(find){
for(var i in cars){
    if(cars[i].make.toLowerCase() === find){
        return cars[i];
    }
    else if(cars[i].model.toLowerCase() === find){
        return cars[i];
    }
    else if(cars[i].year === parseInt(find,10)){
        return cars[i];
    }
    else if(cars[i].condition.toLowerCase() === find){
        return cars[i];
    } 
}
};


cars.findCar = findCar;

//This is where I search for cars
cars.findCar(prompt("Enter a car make, model, year or condition").toLowerCase());
2
  • A function can only return one value in JS, if you want multiple objects, then you can return an array of objects (collection), that you build within the for loop. It would be easier if you start with cars as a collection, not a nested object.
    – elclanrs
    May 31, 2014 at 22:49
  • Should the cars be an Object or an Array? If the keys are going to be things like 'car1','car2','car3' you are better off with an array cars = [] and accessing individual cars through the integer index cars[0], cars[1], cars[2], etc... Now some people do have cute names for their personal cars, which one might think could be keys for an object, except keys have to be unique. The convenience of an array is that you can use Array.push() to add a car without keeping track of how many cars here already are, sort(), and other methods common to collections. Objects dont have these.
    – Paul
    May 31, 2014 at 23:29

2 Answers 2

1

You could store your cars in an array like that :

findCar = function(find){
 var finds = [];
 for(var i in cars){
    if(cars[i].make.toLowerCase() === find){
        finds.push(cars[i]);
    }   
    else if(cars[i].model.toLowerCase() === find){
        finds.push(cars[i]);
    }
    else if(cars[i].year === parseInt(find,10)){
        finds.push(cars[i]);
    }
    else if(cars[i].condition.toLowerCase() === find){
        finds.push(cars[i]);
    }        
 }
 return finds;
};

To avoid repetition :

findCar = function(find){
    var finds = [];
    for(var i in cars){

        //Loop through properties
        for(var j in cars[i]){

            if(cars[i][j] === find){
                finds.push(cars[i]);
                //If found, pass to the next car
                break;
            }
        }
     }
     //Return results.
     return finds;
};

Next step would be to add some regexp to your search.

0

The return keyword will only return one object and that object can be an array. Furthermore, no code will execute in your function after the return is performed, so you must wait until all iterations of your loop are complete before returning anything. Without refactoring any of your logic (there are several other issues) and answering only your question, this is the modified code for your example above:

//The method
findCar = function(find){
    var results = [];

    for(var i in cars){
        if(cars[i].make.toLowerCase() === find){
            results.push(cars[i]);
        }   
        else if(cars[i].model.toLowerCase() === find){
            results.push(cars[i]);
        }
        else if(cars[i].year === parseInt(find,10)){
            results.push(cars[i]);
        }
        else if(cars[i].condition.toLowerCase() === find){
            results.push(cars[i]);
        }        
    }

    return results;
};
2
  • 2
    There shouldn't be any returns inside the for loop if the goal is to search all the cars.
    – Paul
    May 31, 2014 at 23:23
  • This would work, except now I get an error saying "Cannot read property 'toLowerCase' of undefined". I'm pretty sure this has something to do with the array. Is there a way to fix this? Jun 1, 2014 at 0:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.