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

Exploring the capabilities of qTip2 integrated with jQuery Vector Maps (jqvmap)

Is there a way to disable the default tooltip in jqvmap and replace it with qTip2? Check out this example. Here's the jQuery code: jQuery('#vmap').vectorMap({ map: 'world_en', backgroundColor: null, color: '#ffff ...

Change the class upon clicking the element

Looking to create a function that toggles classes on elements when specific links are clicked. For example, clicking on link 1 should add the "active" class to the red element, while clicking on link 2 should do the same for the pink element, and so forth. ...

Converting lengthy timestamp for year extraction in TypeScript

I am facing a challenge with extracting the year from a date of birth value stored as a long in an object retrieved from the backend. I am using Angular 4 (TypeScript) for the frontend and I would like to convert this long value into a Date object in order ...

Create a complete duplicate of a Django model instance, along with all of its associated

I recently started working on a Django and Python3 project, creating a simple blog to test my skills. Within my project, I have defined two models: class Post(models.Model): post_text = models.TextField() post_likes = models.BigIntegerField() post_ ...

Exploring the implementation of Chain Map or Chain Filter within an Angular Http request that delivers a promise

I have a dataset in JSON format that I am working with, and I need to filter out specific key values using lodash. I want to reject multiple keys that I don't need. My initial approach is to either chain the map function and then use the reject funct ...

Is there a way to showcase the generated results on a graph after the user presses the submit button?

I've been working with to generate a bar chart. Currently, when the user clicks 'submit', the input numbers are shown in a graph on http://jsfiddle.net/jx9sJ/5/. Now, I want to make some changes. I am attempting to send the input numbers t ...

Safari's Failure to Execute Ajax Requests

My HTML page includes an ajax request that is functioning properly on Firefox, but does not work on Safari. While debugging, I noticed that the readystate is undefined and the status is "". Can anyone suggest why it might not be working on Safari? Javascr ...

Tips for creating an editable div that can also incorporate a textarea and the option to upload or delete photos

On my website, users can upload images, names, and descriptions which are saved in a MySQL database. The information is then fetched to display on the website. The code below allows users to enter this information and see it displayed when they click the s ...

Embed array inside angular directive

In my angular application, I have a code snippet that generates a navigation tree within a <div>. The size of this tree depends on the contents of mymodule.tree.folders. To enhance this functionality, I want to create a directive named class="scrolla ...

Automatically tally up the pages and showcase the page numbers for seamless printing

I've been tackling a challenge in my Vue.js application, specifically with generating invoices and accurately numbering the pages. An issue arose when printing the invoice – each page was labeled "Page 1 of 20" irrespective of its actual position in ...

Element sticking on scroll down and sticking on scroll up movements

I am currently working on a sticky sidebar that catches and stays fixed at a certain scroll point using JavaScript. However, I am facing an issue where I need the sidebar to catch when scrolling back up and not go further than its initial starting point. ...

Discovering the Active Modal Form in BootStrap: Uncovering the Open Modal Form using JavaScript/jQuery

There are a total of 5 modal forms on my page. My goal is to identify the specific Id of the currently active one. One possible solution involves checking if $('#myModal').hasClass('in');. However, this method requires me to repeat the ...

Is there a way to selectively add elements to the Promise.all() array based on certain conditions?

Here is the code snippet that I have written: I am aware that using the 'await' keyword inside a for-loop is not recommended. const booksNotBackedUp: number[] = []; for (let i = 0; i < usersBooks.length; i += 1) { const files = await ...

The PDFKIT feature ensures that any overflowing data in a row is automatically moved to a new page

A function in my code generates a row of data based on an array. It works perfectly fine for the first page, but as soon as the data overflows somewhere around doc.text("example",70,560), it jumps to the next page. The issue arises when the Y coo ...

Issues encountered when attempting to append the array objects to HTML using $.getjson

Hello, I have a JSON data structure as shown below: [{ "menu": "File", }, { "menu": "File1", }] I have created jQuery code to dynamically add the response to my HTML page like this: $(document).ready(function () { $.getJSON('data.json&a ...

Optimizing File Transfers and Streaming Using Next.js and CDN Integration

As I work on developing a download system for large files on my website using Next.js and hosting the files on a CDN, I face the challenge of downloading multiple files from the CDN, creating a zip archive, and sending it to the client. Currently, I have i ...

Top solution for efficiently capturing and storing user input in a React JS application: Event Handler

I've recently designed an input field for inputting details of items. In order to effectively capture and save the entered information, which of the following event handlers would be most suitable? onClick onChange onLoad onKeyPress ...

The length of the scope variable generates an error

var example = $scope.newgoal.gTitle; console.log(example.length); Even running this short code test, it throws an error message: TypeError: Cannot read property 'length' of undefined I've attempted to find various solutions without succes ...

Unable to assign a value to a property within a JavaScript object

I'm attempting to configure settings for a JavaScript object (my assumption is that it's not a plain JS Object, but possibly an instance of a specific class, though I haven't been able to identify the class). Here's how the object appe ...

What action is triggered on an Apple iPhone when a notification is tapped?

Currently, I am working on a React application and testing it on an Apple mobile phone. One issue I encountered is that when I receive an SMS, the number appears as a suggestion above the keyboard. I want to be able to tap on this number and have it automa ...