How can we incorporate a destructured Array into a Set using a functional approach?

I have a scenario where I want to add the contents of multiple arrays into a Set. For example:

Arrays to combine :

var arr1 = [55, 44, 65];
var arr2 = [22, 11, 33];

The desired Set should look like this: [55, 44, 65, 22, 11, 33]

This is what I attempted:

var arr1 = [55, 44, 65];
var arr2 = [22, 11, 33]
var set = new Set();
set.add(arr1)
set.add(arr2)
set.add([8, 5])
console.log(set);                          

However, all three arrays are added as sets instead of individual numbers.

So, I tried another approach which can be found here: JSFiddle

var arr1 = [55, 44, 65];
var arr2 = [22, 11, 33]
var set = new Set();
set.add(...arr1)
set.add(...arr2)
set.add(...[8, 5])
console.log(set);

Unfortunately, only the first elements of each array get added to the Set.

  • Why does only the first element of each array get added in my second approach?
  • Is there a way to add all elements of an array into a set without iterating through every single element and adding them individually (like using for, map, or forEach)? (If possible)

NOTE: In my actual situation, I do not receive all the arrays at once.

Answer №1

As previously mentioned, one possible solution is to create a new Set by combining two arrays like this:

var set = new Set(arr1.concat(arr2, [8, 5]))

To see this in action, you can test it out here.


However, please note that only the first elements of the array are added to the Set.

According to the documentation, the .add method accepts only 1 argument. So when using ...[8, 5], it will add the first value and ignore the rest.


In my specific situation, I do not receive all the arrays at once.

In such cases, you can convert the set back to an array and then create a new Set like so:

var set2 = new Set(Array.from(set).concat([8, 5]))

You can verify this approach on this link


Alternatively, you can use the spread operator as shown below:

var set2 = new Set([...set].concat([8, 5]))

An updated Fiddle is available for testing, although personally, I find Array.from to be more readable. The choice between the two methods is up to personal preference.

Answer №2

If you prefer not to create a new collection, using a loop is a perfectly valid approach:

var arrayOne = [55, 44, 65];
var arrayTwo = [22, 11, 33]
var setObject = new Set();
var addToSet = setObject.add.bind(setObject);
arrayOne.forEach(addToSet);
arrayTwo.forEach(addToSet);
[8, 5].forEach(addToSet);
console.log(Array.from(setObject)); // The console on StackOverflow can't print sets at the moment
// [55, 44, 65, 22, 11, 33, 8, 5]

Answer №3

According to @Rajesh's suggestion, combining the arrays into one and then creating a set from it seems like a viable solution.

var set = new Set(arr1.concat(arr2.concat([8, 5])));

UPDATE: To include another array later on, you can create a new set for each additional array and then concatenate them together as demonstrated here.

set = new Set([...set, ...newSet])

Alternatively,

set = new Set(Array.from(set).concat(Array.from(newSet)))

Here is the complete example:

var arr1 = [55, 44, 65];
var arr2 = [22, 11, 33];
var set = new Set(arr1.concat(arr2.concat([8, 5])));
var arr3 = [10, 20];
var newSet = new Set(arr3);
set = new Set(Array.from(set).concat(Array.from(newSet)));
set.forEach(function(element) {
  console.log(element);
});

Output:

> 55
> 44
> 65
> 22
> 11
> 33
> 8
> 5
> 10
> 20

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

methods for extracting json data from the dom with the help of vue js

Can anyone help me with accessing JSON data in the DOM using Vue.js? Here is my script tag: <script> import axios from "axios"; export default { components: {}, data() { return { responseObject: "" }; }, asy ...

What are some ways to capture and save the window width prior to launching my Nuxt application?

I am working on a Nuxt application where I need to display different components based on the window width and send a request to create a session with the device width as one of the header parameters. Here is my approach: In my store code: //index.js expor ...

Exploring the world of Django static files, along with the magic of CSS and

Currently running on django 1.3 for production and encountering an issue with using static files in my CSS and JavaScript. Strangely, there are no problems in my HTML code! How can I resolve this dilemma? Unfortunately, the Django documentation does not pr ...

Real-time Updating of ChartJS Charts in Rails Using AJAX

I am currently working with Rails 5 and the latest version of ChartJS library (http://www.chartjs.org/docs/). My goal is to retrieve the most recent 20 items from the SensorReading model and update the Chart using setInterval and AJAX. I have successfull ...

What is the most efficient method for managing components with dynamic templates and their corresponding data in Vue.js?

I have a question and requirement that I would like to discuss. It involves dynamically rendering templates and data using components. The scenario is as follows: The root Vue instance fetches data from the backend, and let's say the following data i ...

Issue with debugging capabilities in Javascript on VSCode has been detected

UPDATE: I'm seeking guidance on configuring VSCode for debugging Javascript. While I'm familiar with JavaScript functioning in a browser, I find it tedious to rely solely on console.log(). I am looking to debug and step through my code effectivel ...

expose-loader fails to reveal changes made to the object being exposed

Currently, I am using Webpack 2, Bootstrap 3, and TypeScript in my project. My goal is to integrate npm and packaged bundles into an existing application seamlessly. To achieve this, I have utilized the ProvidePlugin to ensure jQuery is accessible and the ...

What differences exist between these two methods of writing arrays?

After receiving an answer to a previous question on Stack Overflow (here), I have a conceptual question related to it. While my example is in Java, I believe this question applies to similar languages as well (although I would appreciate confirmation or co ...

How to send form data from Angular to Node.js using $http

I'm encountering an issue with my form where the data is not being sent to my backend: <div ng-controller="searchController"> <form ng-submit="submit()"> <input type="text" name="name" ng-model="namegirl" /> <input type=" ...

Tips on avoiding scrolling when toggling the mobile navigation bar:

While working on a website using HTML, CSS, and BS3, I have created a basic mobile navigation. However, I am facing an issue where I want to disable scrolling of the body when toggling the hamburger button. The problem arises when the menu is toggled on, ...

Transforming an event object from the browser's native form to a jQuery event object

Implementing an event handler function to an element using the native browser onclick property is a crucial part of my current project: document.getElementById('elmtid').onclick = function(event) { anotherFunction(event) }; While working in ano ...

Utilize the existing code to prevent multiple form submissions

My current focus is on integrating a Delete Account feature into my website. If a user requests to delete their account (please note that it takes 3 days to completely delete the data) and tries to log in within this 3-day period, we need to prompt for co ...

What is the process for transforming Unicode symbols into their corresponding emojis?

I have been working on a project similar to the one showcased on this website. I've managed to successfully convert UTF16 into UTF string using the code snippet below: function decodeFBEmoji (fbString) { // Convert String to Array of hex codes con ...

Using JavaScript within SQL allows developers to combine the power

Every year, I need to insert a new primary key into my SQL database that follows a specific format (for example, in 2012 the key is 2012000000, and in 2013 the key is 2013000000). I want this process to happen automatically. My plan is to incorporate a sc ...

Issue with Ant Design form validation

After reading through the documentation, I attempted to implement the code provided: Here is a basic example: import { Button, Form, Input } from "antd"; export default function App() { const [form] = Form.useForm(); return ( <Form f ...

Modifying a single element within a class with Jquery

Is it possible to create a stack of pages on a website using JQuery? I found this image that shows what I'm trying to achieve: image. Instead of applying ID css for each page, I'd like to use JQuery. While researching similar questions, I came ac ...

Is there a way to conceal a component using Twitter Bootstrap while having the ability to reveal it with the help of

Suppose I generate an HTML element in the following manner, <div id="unique-div" class="concealed">Hello, TB3</div> <div id="unique-div" class="hide-me">Greetings, TB4</div> <div id="u ...

Display a solo element from an array sent from Express to an EJS template, along with a "next" button for cycling through each item individually

In this scenario, I have set up a route to retrieve all the items stored in the question array. However, the issue at hand is that I only want to display a single item on the ejs page instead of all the items. Additionally, I would like to include a next ...

Limiting an array and dividing it into multiple arrays in PHP can be achieved by using array_chunk()

My goal is to achieve the following... I have an array containing 50 elements. $data = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43 ...

React: Struggling to render values within {} of a multidimensional object

I'm facing a challenge that I can't seem to overcome and haven't found a solution for. The values between curly braces are not displaying in the Content and Total components. I've double-checked the JSX rules, but it seems like I might ...