I'm a newbie of 1 month trying to understand arrays, and how to access them better, I wish to become a master of the for loop with arrays, as it bothers me that IDK how filter, map, and reduce are doing what they're doing. I'd like to know how to change say the 'M'
in 'Milk'
, to an 'S'
, using a for loop and indices. Why does the i
variable in this log 'Top Shelf'
+ the contents of the sub-array, instead of just Top Shelf, Mid-Shelf, Vegetable Drawer, Meat Drawer
? Why doesn't console.log([i[k]])
list just the contents of the sub-array within Top Shelf
?
let fridge = [['Top Shelf', ['Milk', 'Grapes', 'Margarine']], ['Mid-Shelf', ['Beer', 'Eggs', 'Pizza', 'Soda']], ['Vegetable Drawer', ['Celery', 'Broccoli', 'Carrots', 'Lettuce']], ['Meat Drawer', ['Bacon', 'Turkey', 'Ham', 'Chicken']]];
for(let i = 0; i < fridge.length; i++) {
for(let k = 0; k < fridge[i].length; k++) {
}
console.log(fridge[i[k]])
}
First of all your code doesn't work because k won't be defined as you're attempting to use it outside of the loop it was declared in.
Second - In order to access individual elements and say change the first letter to an 'S', strictly using for loops, you'd do something like this:
for(let i = 0; i < fridge.length; i++) {
let shelf = fridge[i];
for(let j = 0; j < shelf.length; j++) {
let item = shelf[1][j];
let itemSplit = item.split('')
let newItem = 'S'+item.slice(1, itemSplit.length);
shelf[1][j] = newItem;
}
}
console.log(fridge);
Third - if you're getting the results of Top Shelf, [contents]
then that's because you are printing that array totally. The contents doesn't actually belong to the Top Shelf
- they are different elements in the same array so [i[k]]
won't work.