function menuSet(menuArray) {
let flatmenus = menuArray.flat();//Method gom cac Array con va Array cha thanh 1 Array duy nhat
let combinedMenu = new Set();//Tao Object trong do Loai bo cac phan tu con trung nhau
flatmenus.forEach(dish => { //Dua cac phan tu trong Flatmenus vao Object Set() moi duoc tao
combinedMenu.add(dish)
});
const menuCombined = document.querySelector('#combined-menu')
for (let dish of combinedMenu) {
let foodNode = document.createElement('li')
foodNode.innerText = dish;
menuCombined.appendChild(foodNode);
}
}
menuSet([["Tacos", "Burgers"], ["Pizza"], ["Burgers", "Fries"]])
Why for..in loop can not deal with the object but it comes Ok with Set()? Doesn't Set() return an Object?
Why for..in loop can not deal with the object but it comes Ok with Set()? Doesn't Set() return an Object?
I think you meant for...of loop (that's what your code uses), not for...in.
To use for...of on something, it has to be iterable (it has to implement the standard way of getting an iterator from it). Objects are not iterable by default. Array, Set, Map, and String objects are iterable, and you can make your own iterable objects, but plain objects aren't iterable.
I assume you're using Set to remove duplicates ("Burgers" appears twice in flatmenus). You don't need that forEach call to put the values in the Set, you can pass flatmenus into new Set directly:
for (let dish of new Set(flatmenus)) {
// ...
}
That works because the Set constructor accepts an iterable object and adds all of the values from its iterator to the Set. Arrays are iterable.
You can do something like this:
const menuSet=(menuArray)=> {
let flatmenus = new Set(menuArray.flat());
const menuCombined = document.querySelector('#combined-menu')
flatmenus.forEach((dish)=>{
let foodNode = document.createElement('li');
foodNode.textContent = dish;
menuCombined.appendChild(foodNode);
});
}
menuSet([["Tacos", "Burgers"], ["Pizza"], ["Burgers", "Fries"]])
<html><head><body><div id="combined-menu"></div></body></head></html>