0

I have a large array in this format:

var cars = [{"brand":"Honda","year":"2002"},{"brand":"Toyota","year":"2000"},{"brand":"Subaru","year":"2009"}];

The array is very large (I made it small for demo purpose) and I want to organize cars of the same brand into an array, so the brand name will be the key for each sub-array, like this:

carsByBrand[ honda[], toyota[], subaru[] ]

I expected it would be straight forward but it's not so. I've tried several variations of the following code, but everytime it returns:

carsByBrand[item.brand] is undefined

 var carsByBrand = [];

   $.each(cars, function(i,item){
     carsByBrand[item.brand].push(item);
    });

    //console.debug(carsByBrand); //uncomment and look at this if you have Firebug

    alert(carsByBrand.length);

I've also tried carsByBrand[item['brand']], why doesn't this work, and how to do it?

jsBin: http://jsbin.com/orafos

1 Answer 1

3
carsByBrand[item.brand].push(item);

That will only work if the array for that brand already exists, which it does not unless you initialize it first with an empty array.

Try

   brand = carsByBrand[item.brand];
   if (brand) {
       brand.push(item);
   else {    
       carsByBrand[item.brand] = [item];
   }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.