Developing a JavaScript Set within an Array constructor

Just a heads up: For those who are wondering, I am fully aware that adding methods to JavaScript built-in objects is generally considered to be a bad practice.

However, I'm currently in the process of adding a new method to the array prototype for a small personal project:

    Array.prototype.add = function (element) {
      console.log('array before: ' + JSON.stringify(this));
      let arr = this;
      if (arr.length) {
        let set = new Set(arr);
        console.log('set before: ' + JSON.stringify(set));
        console.log('adding element: ' + JSON.stringify(element));
        set = set.add(element);
        console.log('set after: ' + JSON.stringify(set));
      } else {
        arr.push(element);
      }
      console.log('array after: ' + JSON.stringify(arr));
    };

Upon trying to use the new method, the first push works as expected. However, on the second call, the "array before:" log displays correctly with the initial push being part of the array. Unfortunately, when I pass the array to my Set constructor, it results in an empty set, which is evident from both the "set before:" and "set after:" logs showing an empty {}. I'm not sure why the Set won't be instantiated from the array. Any assistance would be greatly appreciated.

Answer №1

JSON.stringify always produces an empty object when used with sets

let mySet = new Set([4, 5, 6]);
console.log(mySet.size);
console.log(JSON.stringify(mySet));

Sets cannot be serialized with JSON.stringify due to their lack of properties. Therefore, it is important to use the correct method to check if a set is empty. Try logging set.size or the set itself instead.

For more information, visit: JSON stringify a 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

Error in Mongodb: Unable to convert value into ObjectId

Currently, I am attempting to retrieve only the posts belonging to users using the following code snippet: router.get("/:username", async (req, res) => { try { const user = await User.findOne({ username: req.params.username }); const ...

How can I save the content from a tiptap editor in a PHP form?

I'm looking to integrate the TipTap editor into a PHP form as a textarea field. I've set up a Vue component and passed it to the blade view. Blade view: <form method="post" action="{{ route('dashboard.edit.postInfo', ...

When trying to upload numerous files, only a single file ends up being

The issue is with the function that is only uploading 1 file instead of all 6 files. It seems to be returning an array $fileDirectories with a dimension of 1, whereas I expected it to have 6 dimensions. The interesting thing is that count($_FILES['fil ...

Implementing an All-Routes-Except-One CanActivate guard in Angular2

In order to group routes within a module, I am aware that it can be done like this: canActivate: [AuthGuard], children: [ { path: '', children: [ { path: 'crises', component: ManageCrisesComponent }, ...

Issues with Mega Menu functionality preventing items from being clickable and links from properly navigating

Recently, I encountered a strange issue related to the integration of a mega menu found at . Unfortunately, despite integrating the mega menu, the Category and sub category links seem unresponsive - they are not directing me to the desired links. I suspec ...

What is the most effective method for transmitting a zip file as a response in Azure functions with node.js?

With the Azure function app, my goal is to download images from various URLs and store them in a specific folder. I then need to zip these images and send the zip file back as a response. I have successfully achieved this by following these steps: Send ...

Display a message indicating no data is available if the specified text is not found within the div

In the code snippet below, there is an input element followed by a div containing multiple child elements: <input type="text" onkeyup="filter()" id="filter_data"> <div id="body"> <div class="child"> Text 1 </div> <div class ...

Can you explain the distinction between var_dump() and print_r() when it comes to displaying an array as a string?

Can you explain the variance in output between var_dump() and print_r() when it comes to displaying an array as a string? ...

Using AngularJS, I can bind the ng-model directive to asynchronously update and retrieve data from

I am currently working with Angular to develop a preferences page. Essentially, I have a field in a mysql table on my server which I want to connect my textbox to using ng-model through an asynchronous xhr request for setting and fetching data. I attempt ...

Adjust the value of a variable within a module using Angular JS

Within my module, I have the code below: var mod; mod = angular.module('ajax-interceptor', []); mod.config(function($httpProvider) { $httpProvider.interceptors.push(["$q", function($q, dependency1, dependency2) { return { ...

Creating a text design that spans two lines using Scalable Vector Graphics (SVG

I am working with an SVG that displays strings pulled from an Array... {"label":"Here is an example of the string...", "value":4}, The text above is shown in an SVG element as... <text>Here is an example of the string...<text> I would like ...

"Exploring the world of custom middleware in NextJs on a localhost

Question regarding nextjs page middleware: the documentation states that the request object should include geo, IP, ua, cookies, and nexturl properties. Visit the link for more information. I am attempting to retrieve the user's location using page m ...

I am unable to populate MongoDB references using Node.js

I need to display the user's location details on the screen. For example: name: "Andy" surname : "Carol" City : "Istanbul" Town : "Kadıkoy" When the getuser function is called, I want to show the City and Town name. This is the implementation: U ...

What is the best way to initiate a class constructor with certain parameters left out?

Currently, I am facing a challenge while trying to pass various combinations of arguments to a class constructor. The constructor has 2 optional arguments. Here is the code snippet: class MyClass { foo(a, b) { return new MyClass(a, b); } bar( ...

Setting a default value in a drop-down menu in a React Native application

Within my array of 5 values in the "Options" props, I want to set a default value of "Please Select" defined in the state. However, when trying to retrieve it in the Value props, an error is occurring with a message saying "Label of undefined". Essential ...

Verify if the currentRoute begins with a specific text pattern (such as something/something/*...) in Angular

I need to prevent a loader from appearing on certain screens, so I used ngIf on routes where the loader is not necessary. Here's the code snippet from app.component.ts : <router-outlet> <app-spinner></app-spinner> <ngx-ui-load ...

I'm struggling to change the color of a plane geometry in three.js, it always ends up black. Can anyone help me with this issue?

I'm currently working on adding a plane to the scene, and here's how I'm doing it: var plane = new THREE.Mesh(new THREE.PlaneBufferGeometry(300, 300), new THREE.MeshPhongMaterial({specular: '#fff',fog: false,color: '#ff9a0 ...

Sending JSON Data from Angular2 Component to Node.js Server

Currently, I am facing an issue where I am unable to successfully insert data into a database using Angular2 and Node.js. Upon running my script, I use console.log(this.address); to verify that I am passing json, and the output in the console is as follow ...

Having trouble retrieving features from a QR code generated with Angularx-qrcode?

I utilized angularx-qrcode in order to create a QR code that displays data from qrInfo. However, I'm encountering the following error: ERROR TypeError: Cannot read properties of undefined (reading 'qrcElement') The code within qr-code-gener ...

AngularJS scope variable not getting initialized inside promise

I've encountered an issue with my code while using CartoDB. The goal is to execute a query using their JS library and retrieve some data. The problem arises when I attempt to assign the result as a scope variable in AngularJS, after successfully worki ...