Exploring the capabilities of Set() and the for..in loop in JavaScript

function removeDuplicates(menuArray) {
  let flatmenus = menuArray.flat();//This method combines child and parent arrays into one unique array
  let combinedMenu = new Set();//Creates an object that removes duplicate elements
  flatmenus.forEach(dish => { //Adds elements from Flatmenus to the newly created Object Set()
    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);
  }
}
removeDuplicates([["Tacos", "Burgers"], ["Pizza"], ["Burgers", "Fries"]])

Why can't a for..in loop handle the object but it works fine with Set()? Doesn't Set() return an Object?

Answer №1

Why does the for...in loop struggle with objects but work fine with Set()? Doesn't Set() just return an object too?

I believe you meant to use the for...of loop (which is what your code employs), not for...in.

In order to utilize for...of with something, it needs to be iterable (meaning it must follow the proper method of obtaining an iterator from it). Objects are not naturally iterable. Arrays, Sets, Maps, and Strings are all iterable, as well as user-created iterable objects, but standard objects do not fall under this category.

If you are using Set to eliminate duplicates (such as "Burgers" appearing twice in flatmenus), you can directly pass flatmenus into new Set instead of utilizing forEach to populate the values in Set:

for (let item of new Set(flatmenus)) {
    // ...
}

This approach functions because the Set constructor accepts an iterable object and adds all the values from its iterator to the Set. Arrays qualify as iterable.

Answer №2

A possible solution is shown below:

const mergeMenus=(menuItems)=> {
  let menuSet = new Set(menuItems.flat());
  const combinedMenu = document.querySelector('#combined-menu')
  menuSet.forEach((item)=>{
    let itemNode = document.createElement('li');
    itemNode.textContent = item;
    combinedMenu.appendChild(itemNode);
  });
}
mergeMenus([["Salad", "Pizza"], ["Burger"], ["Pizza", "Fries"]])
<html><head><body><div id="combined-menu"></div></body></head></html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Events for focusing and blurring top level windows

I'm encountering an issue with a basic frameset setup <frameset rows="100, 200"> <FRAME name="listener" src="frame1.html"> <FRAME name="content" src="http://www.someexternalurl.com/"> </frameset> Within the listener ...

Error: Attempting to assign a value to 'onclick' property of null object [Chrome Extension]

window.onload = function() { document.getElementById('item_save').onclick = function() { var item_name = document.getElementById('item_name').value; var item_size = document.getElementById('item_size').value; v ...

What is the best method for incorporating new data into either the root or a component of Vue 3 when a button is pressed?

One issue I'm facing is the challenge of reactively adding data to either the Vue root or a Vue component. After mounting my Vue app instance using app.mount(), I find it difficult to dynamically add data to the application. As someone new to the fram ...

AJAX, JavaScript, and hyphens

Can anyone help me understand why the ajax statement in my code does not accept the '-' symbol? I've had issues with this before and ended up modifying a lot of things on the backend of my site to use '_' instead, which worked. Is ...

Choose to conceal beneath the table within Bootstrap 4

As a budding web developer, I am currently using Bootstrap 4 in my project. If you take a look at my preview by clicking here and then selecting "Liczba sztuk," you'll notice that I am facing an issue. The items within the select dropdown are gettin ...

Retrieve the Vue.js JavaScript file from the designated static directory

This is my inaugural attempt at creating a web application, so I am venturing into Vue.js Javascript programming as a newcomer. I have chosen to work with the Beagle Bootstrap template. Within my Static folder, I have a file named app-charts-morris.js whi ...

Modifying css background in real-time based on the current weather conditions

Is there a way to dynamically change the background image in CSS based on the weather condition? I'm utilizing the wunderground API to retrieve the weather data, which is stored in the weather variable. I am struggling with how to update the backgrou ...

Instructions on utilizing slideDown() paired with appendTo()

I am looking to implement slideDown() alongside my appendTo() Below is the code I am currently using: $(document).ready(function() { var scntDiv = $('#add_words'); var wordscount = 1; $("#add_words").on("keyup","input[type='tex ...

Using javascript to locate and substitute a word divided among multiple tags - a step-by-step guide

I need to utilize JavaScript to locate and substitute a word that has been separated into multiple tags. For instance, consider the following HTML code: <html> <body> <div id="page-container"> This is an apple. ...

Is it possible to utilize the function(e) multiple times within a single file?

Can the same function be used multiple times in a single file? document.getElementById('one').onlick = function test(e) { var key = e.which; if(key === 13) { document.getElementById('two').c ...

Tips for customizing bootstrap's fixed navbar-default to ensure that the list items align downwards:

Is it possible to customize the bootstrap fixed navbar-default so that the li elements align downward instead of at the top? If you have any corrections or custom solutions, I'd love to see them! Feel free to share your code on platforms like CodePen, ...

Saving data from the Viewbag into a jQuery array or object on the client side

Imagine this scenario: I have a dynamic object called ViewBag, which is essentially a list filled with some results; Scenario 1: User 1 enters and populates the ViewBag.Products object with a list of 50 items; Scenario 2: User 2 enters and fills t ...

The POST request is not functioning. An error has occurred: Unable to retrieve response data - no content is available for the preflight request

Having trouble making a post request from my client side to the back-end. Even with the new movie hardcoded, it keeps returning an error stating that there was a failure in loading the response data. Below is the code for the front-end: //Fetch request t ...

Make sure that the webpage does not display any content until the stylesheet has been fully loaded by

I am seeking to utilize ng-href for loading different Themes. One issue I am encountering is that the unstyled content appears before the stylesheet is applied. I have created a Plunker where I made changes to Line 8 in the last 3 Versions for comparison ...

Error caused by jQuery AJAX call: Receiving a 304 response code causes a problem

I am facing an issue with a script on my localhost that sends a GET request to the same domain. The response I am getting is a 304, which seems to be causing JQuery to treat it as an error. $(document).ready(function(){ $.ajax({ type: 'GE ...

Retrieving data from a script within a React component

How can I access a variable from a script inside a React component? I am performing device detection on Node and sending the resulting object to the client (React) within index.ejs. <script type="text/javascript">window.deviceType = <%- deviceT ...

Creating a JavaScript function to selectively blur elements while leaving one in focus

My goal is to blur all elements on a webpage except for the p#this tag using vanilla JavaScript. I am determined to learn the intricacies of JavaScript, so I'm not looking for solutions involving jQuery or CSS. I came across a potential solution on t ...

What is the best way to ensure that a div containing lengthy text wraps to the next line as if it were only text overflow?

Is there a way to make a div or span within another div act as text, causing overflow to shift to the next line? I'm unsure of which CSS properties would achieve this effect. I've attempted using overflow-wrap: break-word; word-break: break-al ...

When there is content behind the list, the Autosuggest Ajax does not function properly

I have successfully implemented an ajax/jquery dropdown/list feature that retrieves results from the database based on user input. For each result in the database, it generates a <li> element and converts it into a clickable link to redirect users t ...

Show or hide text when list item is clicked

This is the rundown of services <div> <a href="#hig"><button class="tag-btn">High blood pressure Diabetes</button></a> <a href="#hih"><button class="tag-btn">High ch ...