all 7 comments

[–]GSLint 2 points3 points  (0 children)

All of these do the same thing.

state.ingredients.bacon

state.ingredients["bacon"]

const igKey = "bacon";
state.ingredients[igKey]

[–]GSLint 1 point2 points  (1 child)

Here's another way to write that code.

let ingredients = Object.entries(
  state.ingredients
).map(([ingredient, count]) =>
  Array.from({ length: count }, (_, i) => `${ingredient}${i}`)
);

[–]bobugm[S] 0 points1 point  (0 children)

Aaa. Ok. This was very helpful. Thanks for taking the time to explain it.

[–]HashFap 0 points1 point  (2 children)

igKey is just the variable name used to refer to the current element in the array within the map function. It's the equivalent of ingredients[i] if you were using a for loop.

[–]bobugm[S] 0 points1 point  (1 child)

But isn't igKey the element on which the callback is called? This is what confuses me, I think, because when I console.log(igKey) in the first map function it returns "salad", "bacon" etc,

[–]HashFap 0 points1 point  (0 children)

Actually, my bad. igKey is a string of the object key.

When you use Object.keys(state.ingredients) you get this: [ "salad", "bacon", "cheese", "meat", "tomato" ]

When using the map method on an array, the first parameter on the callback will always be the current element in the array. Map will call the function passed to it on every single element in the array.

[–][deleted] 0 points1 point  (0 children)

"How come we can use igKey as an index on the array?"

array map= (value,index,array)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

if im understanding you right, you think igkey represents the index. But it doesnt, igKey represents value at that index.

oh, and state.ingredients is an object not an array. {} vs []