javascript - Making a count object by initializing properties from iterating through elements in an array -
alright, i'm working on final problem of javascript-koans. code , dataset i'm given follows:
products = [ { name: "sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsnuts: false }, { name: "pizza primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsnuts: false }, { name: "south of border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsnuts: false }, { name: "blue moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsnuts: true }, { name: "taste of athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsnuts: true } ]; it("should count ingredient occurrence (imperative)", function () { var ingredientcount = { "{ingredient name}": 0 }; (i = 0; < products.length; i+=1) { (j = 0; j < products[i].ingredients.length; j+=1) { ingredientcount[products[i].ingredients[j]] = (ingredientcount[products[i].ingredients[j]] || 0) + 1; } } expect(ingredientcount['mushrooms']).tobe(); });
i think understand of what's going on: we're iterating through products array iterate through ingredients array of each product, taking ingredient, , using bracket notation call property ingredientcount object. around here i'm losing it, because set equal or zero, add 1 regardless. can correct me on have wrong there , explain i'm missing? how/where calling ingredientcount variable 'mushrooms' in bracket notation establish 'mushrooms' in expression? , how incrementing ingredientcount's {ingredient name} property without explicitly referencing it? there kind of implicit assignment or going on?
also, test runner returns error letting me know expected result should 2.
i figured out. right in written summation of code, except we're looking @ in code isn't expression, more importantly it's variable assignment. on each iteration through each ingredient of each product we're initializing new property in ingredientcount object , setting equal or zero. why that? because if set non-existent object's property equal undefined--it doesn't initialize. luckily, undefined falsey value, , if property non-existent instead gets initialized being set zero, incremented one. after each additional count each existing ingredient takes truthy numerical value (skipping 0 after or) , adds one. when @ result console, see ingredientcount object isn't behaving function (as confused in thinking had been), instead it's simple object properties can access give individual counts:
[object object] { artichoke: 1, black beans: 1, blue cheese: 1, garlic: 1, goats cheese: 1, jalapenos: 1, kalamata olives: 1, mushrooms: 2, roma: 1, rosemary: 1, sesame seeds: 1, spinach: 1, sundried tomatoes: 2, walnuts: 1 {ingredient name}: 0 }
{ingredient name} in code placeholder, why shows there @ bottom.
Comments
Post a Comment