Upon experimenting with this sample, I found myself perplexed by the fundamental concepts of Maps and Sets in Javascript

I'm looking to gain a better understanding of the differences between Map and Set by applying some examples. However, I find the behavior of each to be quite confusing. Let's take a closer look at the examples and their respective outputs below.

Map example:

let nameMap = new Map([
  ['name', 'stack'],
  ['name', 'overflow'],
  ['domain', 'technology']
]);

// iterate over keys (nameMap)
for (let name of nameMap) {
  console.log(JSON.stringify(name)); 
}

output:

["name","overflow"]
["domain","technology"]

Set Example:

let nameSet = new Set([
  ['name', 'stack'],
  ['name', 'overflow'],
  ['domain', 'technology']
]);

// iterate over keys (nameSet)
for (let name of nameSet) {
  console.log(JSON.stringify(name));
}

output:

["name","stack"]
["name","overflow"]
["domain","technology"]
  1. Why does map only return the second occurrence of two similar objects?
  2. Set returns all three objects even though the first two keys and values are the same, when it should actually remove one of them. Why is this happening?

Answer №1

I am curious why the map function only returns the second occurrence of two similar objects?

The reason for this is that a Map in JavaScript contains a set of key-value pairs, where each key can only have one corresponding value. When constructing the map using arrays to represent key-value pairs, if the same key is used more than once, the second value associated with that key will overwrite the first value.

On the other hand, when using Set, all three objects are returned even though the first two keys and values are the same. Is this the expected behavior?

In contrast to Map, a Set in JavaScript stores unique values, meaning duplicate values are not allowed. Each array provided to the Set, such as ['name', 'stack'], represents a single value within the set.

Answer №2

Comparing Sets to arrays, they both function as containers for storing values in a sequential order. When initializing a new Set instance using the constructor with multiple arrays, all the elements from these arrays are added as unique values within the Set. On the other hand, the behavior of the Map constructor is akin to that of the Object.fromEntries method - where the first element in each nested array becomes the key and the second element represents the corresponding value. It's important to note that Sets only store values, not keys. Therefore, in order to prevent duplication within a Set, both items in the pair must be identical primitives.

Answer №3

When it comes to data structures, a Map serves as a repository for key-value pairs. Specifically in your scenario, the keys will be represented by name and domain. It's important to note that each key can only appear once in the Map, leading to the deduplication of the name key.

On the other hand, a Set functions as a collection of unique values where duplicates are automatically removed. Given that there are no duplicate values present in your input, all values will be preserved when stored in the Set.

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

Access SCSS variable values in Angular HTML or TypeScript files

So, I've been looking into whether it's feasible to utilize the SCSS variable value within HTML or TS in Angular. For instance: Let's say I have a variable called $mdBreakpoint: 992px; stored inside the _variable.scss file. In my HTML cod ...

Struggling to transfer the loaded data into the corresponding text fields for display

I'm currently working on a project where I need to extract data stored in an object and showcase it on my website. In my .html file, I have the following setup: <script type="text/javascript"> var res = {"address":"","city":"","state":"","z ...

establish a compacted directory shortcut within alfresco

Although I'm not highly skilled in Javascript, I am in need of creating a webscript for Alfresco that can generate an alias [A] for a folder (space) [B]. If the structure of [B] appears as companyhome/site/special/my/fo/ld/de/r, [A] should be struct ...

What is the best way to establish anchors for *ngFor elements in Angular 2 and beyond?

I have a component that displays items using *ngFor. My goal is to scroll down to the element with anchor #3. Here's the code snippet: @Component({ selector: 'my-app', template: ` <button (click)="scroll(3)">scroll 2</butt ...

Experiencing an issue of receiving an undefined value while attempting to retrieve a value from an input box

HTML: <input value='Rename' type='button' onclick='RenameGlobalPhase({$row['id']});' <span id='renameGlobalPhase{$row['id']}'>" . $row['phase'] . "</span> Below you wil ...

add array to a specific field in SQL database

Currently working with the codeigniter framework, I have an array that I would like to insert into a database with columns named sibbling_name and sibbling_age. I followed a tutorial in CodeIgniter, but encountered an error because the fields in the datab ...

JavaScript Callback Functions are Unable to Execute WebSQL Transactions

Currently utilizing PhoneGap in combination with jQuery Mobile, my goal is to retrieve JSON data from a remote source and then populate a local WebSQL database with said information. Below is the JavaScript function for this task: function getLocations() ...

Creating nested directories in PHP using arrays: A step-by-step guide

When working with Laravel, I encountered an issue while trying to create a trait file using the console. The problem arises when specifying a directory for the file creation - it does not get created as expected. The structure of the directory can be dyna ...

Which codec strings are considered valid for the web codecs API?

I am searching for a definitive list of valid strings that can be passed as the `codec` parameter in `VideoEncoder.isConfigSupported({ codec, width, height })`, but I have been unable to find a clear answer so far: The TS declaration file states that it m ...

What could be causing my socket to enter a never-ending loop?

Client Side Code: useEffect(() => { socketRef.current = io.connect("...", { transports : ['websocket'] }) socketRef.current.emit("online", id) socketRef.current.on("message", ({ name, message }) => ...

Is the button inactive until an action is taken?

In my coding project, I am working with two buttons. I am trying to figure out a way to disable the second button until the first button is clicked. Does anyone have any suggestions on how to achieve this using a combination of JavaScript and CSS? ...

Several SVG Components failing to function properly or displaying differently than anticipated

I've encountered a puzzling issue that I just can't seem to solve. Here's the scenario: I'm working on a NextJS App and have 5 different SVGs. To utilize them, I created individual Icon components for each: import React from 'reac ...

``Change the color of the sections in a 3D pie chart on a Highcharts

I am looking to create a custom pie chart with two different colors: one for the main surface and another for the sides. Currently, I can only configure the lighter blue color for the main surface, but I would like to also change the darker blue color for ...

Ways to merge two select options in a form

I'm attempting to merge the selections from two dropdown menus in a form into one variable before submitting the form. Here is an overview of my code: In new.html.erb (for RoR): <%= form_for :character, url: characters_path, method: :post do |f| ...

What is the best way to inform the DOM about newly generated elements dynamically?

When making an AJAX call and generating HTML on the backend side, the result may not display with the desired properties such as cursor styling. For example, using jQuery to render JSON data: $(data.message).each(function (index, value) { $('#sta ...

problem with the clientHeight attribute in window event handlers

The component below is designed to react to changes in window resize based on the container height. However, there seems to be an issue where the containerHeight variable increases as the window size decreases, but does not decrease when I make the window ...

Establishing the value of "document.cookie"

Encountering issues while trying to set a cookie using different methods: Method 1: document.cookie = name + "=" + value + "; expires=" + date.toUTCString() + "; path=/"; This method only sets the value up to "name=value" wh ...

Inserting a Div Element into a List Using a User-Entered Variable (jQuery)

For a school project, I am currently working on a task involving multiple "Add Task" buttons with prompts that appear when clicked. The goal is to have the entered item added to the bottom of the corresponding list. I have experimented with options like a ...

Verify the position of the scrollbar without triggering any reflow

Here is a function I have: is_bottom: function() { if (settings.scrollBottomOffset === -1) { return false; } else { var scroll_height, scroll_top, height; scroll_height = ...

Obtaining data from an external ng-repeat element

My list contains items that are being repeated using ng-repeat details. I want to be able to hover over one of the li elements and have the background of a div called background (which is outside of the ng-repeat) change to the url of the corresponding d ...