Develop a collection of collections using JavaScript

I have a collection of arrays that require deduplication. The process needs to ensure that each individual array contains only unique elements, and across the entire collection, no two arrays are identical in terms of their contents.

Dealing with the first part is straightforward - I can utilize the Set object to remove duplicates from each inner array. To achieve this, given the matrix arrays, I could use the following code snippet:

const sets : string[][] = arrays.map(arr=>[...new Set(arr)].sort());

This code will result in an array of unique sets. But now the challenge lies in turning this into a set of sets. For example, if sets=[[a, b],[c],[d, a],[c],[e]], I want setOfSets to be equal to [[a, b],[c],[d,a],[e]].

Simply applying setOfSets = [...new Set(sets)]; won't work due to the fact that arrays are considered unequal by default even if they contain the same values but reside at different memory addresses. Is there a way to make the Set object compare arrays based on their values or perhaps another approach to achieve the desired outcome?

Edit

Original matrix:

[[a, b, b],
[c,c],
[b,a],
[d,a],
[c,c],
[e,e]]

post generation and sorting of sets:

[[a,b],
[c],
[a,b],
[d,a],
[c],
[e]]

desired result:

[[a,b],
[c],
[d,a],
[e]]

Answer №1

If you find that serializing the data in your set is a straightforward task, one solution worth considering is as follows:

const data = [
  ["a", "b", "b"],
  ["c","c"],
  ["b","a"],
  ["d","a"],
  ["c","c"],
  ["e","e"]
];

// Create the "hash" of your set
const serializeSet = s => Array
  .from(s)
  .sort()
  .join("___");

// Create a map (or object) that ensures 1 entry per hash
const outputMap = data
  .map(xs => new Set(xs))
  .reduce(
    (acc, s) => acc.set(serializeSet(s), s),
    new Map()
  );

// Turn your Map and Sets back into arrays
const output = Array
  .from(outputMap.values())
  .map(s => Array.from(s));
  
console.log(output);

To create an effective hash function for your set, understanding your data is crucial. For instance:

  • For arrays containing single characters from a-z, using the sort method on these strings with a default sorter followed by joining them with a character outside the a-z range may be suitable.
  • If your arrays contain random strings or numbers, consider utilizing
    JSON.stringify(Array.from(s).sort())
    .
  • In cases of arrays consisting of plain objects, employing JSON.stringify on its sorted elements is advised, but be cautious of discrepancies in the order of object properties (e.g., {a: 1, b: 2} versus {b: 2, a: 1}).

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

Every time I attempt to log into my app, I encounter a persistent 401 error message

I've implemented a user/login route that retrieves a user, compares their password with a hashed version, creates a token, and sends it to the front end. However, I encountered a persistent 401 error in the console on the front end, leading to the fin ...

The result of Coordinates.speed is consistently null

I'm working on a project that involves changing the speed of background particles based on the user's device speed (like when they are in a car or bus). I thought the Geolocation API would be a perfect fit, specifically the Coordinates.speed prop ...

Tips for displaying or concealing a specific block by clicking on an element

I have a list-menu called .sidebar-menu and each li within this list has its own unique id. There is also a block called .services-info, containing several blocks with one of them supposed to appear when you click on an item in the .sidebar-menu that corre ...

Retrieving values using the jQuery .each() function and passing them to an AJAX request

Is it possible to set jQuery AJAX outside of .each in the script provided below? $('#btnUpdate').click(function() { $('#result').html(''); $('.moduleIDInput').each(function() { var uid = $(this). ...

Organize and Group Matching Strings in an Array using Node.js

I'm currently developing an FAQ system that includes a large number of question-answer pairs. My goal is to group similar questions together and I've been utilizing the npm set-clustering package for this purpose. While the package offers a good ...

AngularJS: Organizing Controllers Horizontally Within ngRepeat

My data consists of a table with 100 rows, each representing a complex object that is an instance of a specific type. User interactions trigger operations on these objects individually, with each row having unique operations independent of the others. $sc ...

Displaying server errors in an Angular componentIn this tutorial, we

As I work on creating a registration page, my focus has been on posting data to the server. I have successfully implemented client-side and server-side validation mechanisms. Managing client-side errors is straightforward using code such as *ngIf="(emailAd ...

The deletion of elements in an array using $timeout is experiencing issues with functionality

After 5 seconds, the directive notification should automatically delete itself. However, there seems to be an issue where some elements are missed and others get deleted more than once. Each notification has a unique identifier property. Thank you for any ...

Storing Iframe content without the need for a "save button" in a colorbox

I'm currently working on a small project that involves a main HTML page and a separate settings.html file. I've set it up so that the settings page pops up when clicked, using the following code: jQuery('#settings').colorbox({iframe:tr ...

Javascript Events with a Time Limit

Is there a way to create timers in JavaScript that can trigger certain events in the code and be used as conditions elsewhere without relying on libraries? I need these timers to control the timing of events within the program, such as triggering actions ...

I am looking to modify the background color of the columns in an Ant Design table based on whether the index of my data is even or odd

I am trying to change the background color of the columns in an Ant Design table based on the index of my data being even. Can anyone provide suggestions on how to achieve this? I have my data in a list and I want to set a condition through a loop to cha ...

Deliver an index.html file upon server creation

My goal is to have the server load a file called index.html when it is created. Currently, when I run the server.js file using node, it responds with text using res.end("text"). However, I want the index.html file to be displayed instead. I attempted to a ...

Utilizing Angular 5: Enhancing ngFor with a Pipe and a Click Event

Iterating through an array of objects using *ngFor, I apply various filters via pipes to manipulate the resulting list. One of these pipes relies on a user input from a search field. Upon clicking on one of the ngFor elements, the corresponding object is p ...

Leveraging JavaScript to Invoke C++ Code in Internet Explorer

While BHO extensions allow JavaScript to call functions in a C++ BHO, I am exploring a different scenario. Imagine that instead of using a BHO, I have a C++ console application that creates an IE COM object like this: HRESULT hr = CoCreateInstance( ...

You are unable to link two requests within a single route

When working with my node API, I encountered a need to call an external API. To accomplish this task, I am utilizing the request-promise-native library. An example of a route that functions as expected is as follows: router.get('/update/:id/:value&a ...

Tips for adding multiple fields to an element in an array using the useState hook

const[formData, setFormData] = useState({ field1 : [{ f1: "", f2: "", }], field2: [{ f3: "", f4: "", }] }) How can I efficiently update and add new elements to both field1 and field2 in the above code snippet? ...

Tips on retrieving the URL of a background image using "$event.target" to display in an Ionic modal

How can I display the clicked image in a modal? Implementation: <a ng-click="openModal($event)" ng-style="{'background-image': 'url(assets/img/img-01.jpg)'}"><img src="assets/alpha-4x3.png"></a> <a ng-click="openM ...

When trying to access data within objects using JSON iteration, it may lead to encountering an issue of reading a

Attempting to retrieve specific data from a JSON file obtained from a website has proven challenging. While iterating through the collection of objects, undefined values are constantly encountered. Unfortunately, if the JSON is poorly structured, modificat ...

What strategies can be implemented to minimize the use of if-else statements?

Is there a more efficient way to simplify this if-else statement? This code dynamically changes the picture based on integers retrieved from the database. I am looking for ways to optimize this code. if (val["soil_h"] < 21){ $("#ground").att ...

Click on the image to send the form

Is it possible to submit a form by clicking on an image without using jQuery? The code snippet provided below is not working for me. Can you suggest an alternative method? Razor @using (Html.BeginForm("AssignLabels", "Home", FormMethod.Post, new { name = ...