ES6 Set enables the storage of multiple occurrences of arrays and objects within

Review the script below. I'm currently testing it on Chrome.

/*create a new set*/
var items = new Set()

/*add an array by declaring its type as an array*/
var arr = [1,2,3,4];
items.add(arr);

/*display items*/
console.log(items); // Set {[1, 2, 3, 4]}

/*add an array directly as an argument*/
items.add([5,6,7,8]);

/*display items*/
console.log(items); // Set {[1, 2, 3, 4], [5, 6, 7, 8]}

/*display the type of items stored in Set*/
for (let item of items) console.log(typeof item); //object, object

/*check if the item contains the array we declared as an array*/
console.log(items.has(arr)); // true

/*Now, check if the item has the array added through arguments*/
console.log(items.has([5,6,7,8])); //false

/*Now, add the same array again via argument*/
items.add([1,2,3,4]);

/*Set now contains duplicate items*/
console.log(items); // Set {[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4]}
  1. Why is it returning false at items.has([5,6,7,8])?
  2. Why does it allow duplicate values? Isn't "A set is an ordered list of values that cannot contain duplicates"?
  3. How can I access the array added with items.add([5,6,7,8])?

Answer №1

  1. Why is it returning false when using items.has([5,6,7,8])?

    According to information from MDN

    The Set object allows you to store unique values of any type, whether they are primitive values or object references.

    Objects in the set are compared based on their reference and not their value. Sets utilize the SameValueZero(x, y) comparison algorithm to determine equality. It states Return true if x and y refer to the same Object value. Otherwise, return false.

  2. Why does it allow duplicate values? I thought "A set is an ordered list of values that cannot contain duplicates"

    This is similar to #1. A non-primitive value is considered a duplicate in the set only if the same object (not just a similar-looking one) has already been added.

  3. How can we access the array added with items.add([5,6,7,8])?

    You need to create a variable and add that variable to the set. Then you can use this variable to check if the set contains that specific array or not.

Answer №2

According to the guidelines:

Set objects are groupings of ECMAScript language values where each value is unique within the Set. The comparison algorithm used to distinguish these unique values is SameValueZero.

(emphasis added)

The SameValueZero comparison algorithm defines its behavior when comparing two arguments of the same type (excluding null, undefined, strings, numbers, booleans, or symbols) as follows:

If x and y have the same Object value, return true. Otherwise, return false.

In essence, this means that objects are compared based on their reference (i.e., do they point to the same memory location?). Each time a new array is created using brackets ([]) or constructor invocation (new Array()), a new instance of that array resides in memory. Comparing a reference to itself will result in a match (e.g. arr === arr). However, creating separate instances of arrays and comparing them will not result in a match, even if their contents are identical (e.g. [1, 2, 3] !== [1, 2, 3]).

Answer №3

  1. When comparing arrays, it is important to note that the comparison is based on references rather than values, which is why [1] === [1] will always return false.
  2. To learn more about this topic, check out the reference at MDN

The Set object allows you to store unique values of any type, whether they are primitive values or object references.

By passing a new object instead of a reference, duplicates can be added visually similar but with different references.

  1. To access the added array, pass the reference by assigning it to a variable.

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

Bootstrap dropdown menu experiencing functionality issues

I am facing an issue with implementing the javascript bootstrap file in my project. The dropdown menu is not working as expected even though I have saved bootstrap to my project folder. I have tried looking at other example codes and even copied and paste ...

Why isn't my ng-click function functioning properly on Google Maps in AngularJS?

i have two stores in my database and am attempting to display them on a Google map with markers. I have an ng-click function inside the info window to pass the store id, but it seems like ng-click is not working. Is there any alternative method to pass t ...

Transmitting occasional feedback from ASP.NET Web API function to jQuery AJAX

I am currently working on a project that requires sending intermittent status responses from a Web API method back to a jQuery AJAX call in order to display progress in the UI. The process involves the jQuery AJAX calling the Web API method with specific ...

Tricks for displaying a dynamic object tooltip in Three.js

Can anyone help me figure out how to create a HUD hint effect for a moving object? I envision something like this: An asteroid is floating through space, and when I click on it, a hint box with information pops up. I've been playing around with thi ...

The callback function in AngularJS filters

I'm currently using an AngularJS filter to sort through a list of items. Here is the Jade markup I am using: li(ng-repeat="parcel in parcels | filter : filterActiveAreaParcels") After the filter function runs and the elements are displayed in the DO ...

Cracking the code of the @ symbol within this particular context

https://github.com/react-dnd/react-dnd/blob/master/examples/04%20Sortable/Simple/Card.js I'm trying to comprehend the significance of the @ symbol in this example. This is meant to be a straightforward drag and drop demonstration, but the implementa ...

Determining if an array is devoid of any elements using ng-if

When the API I am dealing with has no items in the array, it returns: items: [] If there are elements in the array, it looks something like this: items: [ { name: 'Bla' } ] I suspect that in my template, I will need to utilize ng-if t ...

Having trouble getting Fullcalendar to show up on my cordova app

Currently, I am in the process of building a mobile application using ionic and cordova. My goal is to incorporate a timetable system utilizing Fullcalendar and a PHP page that showcases MySQL data in JSON format. Despite my efforts, I am encountering diff ...

The concept of undefined functions and the use of dependency injection may not always align

Recently starting with AngularJs, I am honing my skills by developing a single page Todo Application. However, I have encountered an issue while trying to load a localStorage factory that I intend to use for this project. Currently, I am stuck on the error ...

Tips for overcoming indentation issues using ESLint?

Ever since I started using Vue 3 with ESlint, I've been encountering a new problem. Whenever I try to run my code, I am bombarded with numerous errors like: --fix option.</p> I'm looking for ways to disable this troublesome feature of ESl ...

Identify when an ajax request is completed in order to trigger a subsequent ajax request

Within my project, I am faced with a challenge involving select option groups that dynamically load ajax data based on previous selections. The issue arises when I attempt to replicate this functionality for another select option group. Here is the scenar ...

When the buffer is sent through the socket in NodeJS, the console responds by stating that it is not recognized as a buffer

I've been exploring the implementation of AES encryption in ECB mode and here is the code snippet I'm working with. function encrypt (key, iv, plaintext) { if(algorithm == 'aes-128-ecb') iv = new Buffer(''); var ciphe ...

Error encountered while trying to eliminate array element

I have a project in the works that involves creating a page where users can filter suggestions and vote for their favorites. The screen is divided into 3 tabs: [Top Rated], [Newest], and [My Votes]. Upon loading the screen, a call to the database is made ...

NodeJS Error: Attempting to access 'json' property from an undefined source

I'm in the process of setting up a CronJob to make an API call and save the response into the database: const CronJob = require("cron").CronJob; const btc_price_ticker = require("../../controllers/BtcExchange/Ticker"); const currency = require("../.. ...

One of my AngularJS directives seems to be malfunctioning while the rest are working fine. Can you help me troubleshoot

Recently, I've been immersing myself in the job search process and decided to create a website as a sort of online resume while also learning AngularJS. I enrolled in the Angular course on CodeSchool and am slowly building my website to my liking. (Pl ...

How to upload an Image to Cloudinary using Express.js, React, and Axios for a POST

I encountered an issue while attempting to upload images to Cloudinary using a React front-end and Express server. The problem lies in not being able to properly post request the image to my Express server. Here is how I prepare the image for sending it l ...

I'm looking to dynamically populate a DropDown list by utilizing Ajax in conjunction with a C# method. Can

Greetings, I have developed a C# method which looks like this: [WebMethod] protected static void populateDropdown(HiddenField hiddenControl, System.Web.UI.WebControls.DropDownList listinc) { int data = 0; string query; dat ...

Schema for Monogo Database

My goal was to have a property that could give me the timestamp of when a specific task was created. I decided to add a timestamp property and set it to true, but now my code won't compile. The code is functioning perfectly fine without the timestamp ...

Recognizing JavaScript in Intellij IDEA within a script tag that does not specify the type as "text/javascript"

Using the MathJax javascript library has presented a challenge for me. Whenever I make changes to the MathJax configuration, I encounter issues because it is written in javascript but its type is labeled as "text/x-mathjax-config". This causes Intellij Ide ...

Using JavaScript variables within the value section of a JSON is a common requirement for developers

var averageTemperature = req.params.rating; var destinationName = req.params.name; var query = { "results.name": destinationName }; var updateQuery = { $set: { "results.$.rating": averageTemperature } }; mach.update(query, updateQuery, function(err, res ...