Can someone recommend a streamlined JavaScript algorithm for identifying the unique arrays within a collection of arrays?

Consider the array below:

let array = [[1, 2], [1, 2], [3, 4], [5, 6], [2, 1]]

I am looking for a way to determine the number of unique arrays in this set. Using the array above as an example, the expected result is 3. How can I achieve this? The code snippet provided below was my attempt, but it doesn't yield the correct output.

let distinct = 0
for (let i = 0; i < array.length; i++) {

  for (let j = i + 1; j < array.length - i; j++) {
    let difference = ingredients[i].filter(x => !array[j].includes(x))
     if (difference.length > 0) {
       distinct += 1;   
     } 
   }
 }

 return distinct;

Answer №1

Importance of Order in Sub Items

To preserve the order within sub-items, utilize Array.map() to transform each sub-array into a string, employ String() as recommended by @trincot on this source, generate a Set from the array to eliminate duplicates, and ascertain the size of the Set:

const array = [[1, 2], [1, 2], [3, 4], [5, 6]]

const distinct = new Set(array.map(String))

console.log(distinct.size)

If Order is Irrelevant

If the sequence does not matter, arrange each sub-item, then convert it to a string:

const array = [[2, 1], [1, 2], [3, 4], [5, 6]]

const distinct = new Set(array.map(o => String(o.sort())))

console.log(distinct.size)

Answer №2

I just went over your syntax and made the necessary corrections without looking at your algorithm. Have I captured what you intended to write?:

let array = [
  [1, 2],[1, 2],[3, 4],[5, 6]
];

console.log(countDistinctArrays(array));

function countDistinctArrays(parentArray) {
  let distinct = 0;
  for (let i = 0; i < parentArray.length; i++) {
    for (let j = i + 1; j < parentArray.length - i; j++) {
      let difference = parentArray[i].filter(x => !parentArray[j].includes(x))
      if (difference.length > 0) {
        distinct += 1;
      }
    }
  }
  return distinct;
}

Answer №3

If you attempted this task, here's a different approach. First, convert the inner arrays to strings, remove any duplicates, and then parse the strings back into arrays.

var arr =  [[1, 2], [1, 2] ,[3, 4] ,[5, 6]];
var uniqueArrays = arr.map(ar=>JSON.stringify(ar))
  .filter((item, index, array) => array.indexOf(item) === index)
  .map(str=>JSON.parse(str));

console.log(uniqueArrays.length);

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

Creating a well-aligned form using Material-UI

Exploring Material-UI for the first time! How can a form be built where certain fields are arranged horizontally, others stacked vertically, and all aligned perfectly both vertically and horizontally? Check out this example image: https://i.sstatic.net/5R ...

Unable to establish connection with Uploadthing due to a timeout error

I am facing timeout errors while setting up the upload feature. app/api/uploadthing/core.ts import { createUploadthing, type FileRouter } from "uploadthing/next"; import { auth } from "@clerk/nextjs"; const handleAuth = () => { c ...

d3: It appears that my routes are replicating themselves, and I am unable to ascertain the cause

I've been diving deep into D3, studying the works of Mike Bostock and other experts in the field. I'm also going through Scott Murray's book on Interactive Data Visualization specifically focusing on D3. At the moment, my project involves c ...

Enhancing Material UI v4 Themes using TypeScript

I am attempting to implement my own custom palette option in the theme section, but I am struggling with how to do the augmentation part using TypeScript. So far, I have created a file named "material-ui.d.ts" and inside it, I only have: import { PaletteO ...

Sorting method in Ext JS 6.2.0 using mode

Seeking clarification on the sort([field],[direction],[mode]) method in Ext JS 6.2.0. Can someone explain the distinction between append, prepend, replace, and multi as mentioned in the documentation available at this link? I am unable to find a clear expl ...

Guide to substituting the index value with the user's specific choice

Let's simplify this. Suppose I have a list in my ng-repeat 1. A & index[0]<br> 2. B & index[1]<br> 3. C & index[2]<br> 4. D & index[3]<br><br> and there is an input field where the user can priorit ...

Is your angularjs localstorage giving you trouble?

I am encountering an issue with local storage on my webpage. Upon initial visit, I am seeing an outdated value from local storage. However, upon refreshing the page, I am able to access the current value. How can I prevent this error and ensure that I only ...

Dynamic class name changes in Angular.js based on JSON object

I am trying to dynamically change the class of an <li> element based on the category value I am getting, but for some reason the class name won't update. Here is the code snippet: <div id="content"> <ul id="container" ng-controller ...

Navigating the jQuery UI Accordion: selecting a panel via the top menu to reveal its contents while simultaneously closing any

Being a native French speaker, I ask for your understanding regarding any English errors made. Additionally, while I am comfortable with (x)HTML and CSS, I am a complete beginner in jQuery. My current project involves setting up a jQuery UI Accordion with ...

Storing the timestamp of when a page is accessed in the database

I am currently working on a PHP website where users can register and access exclusive Powerpoint presentations. The owner has requested that I track the amount of time users spend viewing each presentation, but I am unsure of how to display and record th ...

Enhancing Online Presence with Video Gallery Website Development

I'm in the process of creating a website and need help finalizing my video page. I envision a layout similar to this example: https://i.stack.imgur.com/hctui.gif The main feature should be a large video placeholder at the top, followed by several thu ...

Fetching data from MongoDB, loading over 3000 entries and implementing pagination

I'm facing a challenge where I need to display more than 3000 results in an HTML table by fetching MachineID, Username, and Data from my MongoDB. However, I am encountering difficulties when trying to render this data using datatables. The MachineID ...

Ways to execute a loop matching the size and contents of an array

The rover's behavior input will be something like LMLMLM, which will then be stored in an array as ["L", "M", "L", "M", "L", "M"]. I need to apply the if statements in the rover's behavior to each character in the array. For example, if the input ...

Menu options

I am currently working on developing a mouseover navigation website. Initially, my design included main buttons for "Our Team", Locations, and Patient Resources. Here is the basic structure I had before attempting to switch to a mouseover approach... &l ...

Phone browsers are not executing the jQuery append function as expected

My Flask application utilizes jQuery to dynamically generate data line by line from a SQLalchemy database. I have a forEach loop set up to create each element based on the size of the database. Strangely, this method works flawlessly on all desktop browser ...

ng-view scope interacting with parent scope connection

Excuse the late-night desperation, but I have a question about my AngularJS application that uses ngRoute. Currently, everything is being handled in one controller. The issue arises with a form in a view where I need to take the input field data and store ...

Having trouble setting the selected option in Jquery by value?

I have exhausted all options found on the internet. What could I be overlooking? The desired option is not getting selected. Here is the troublesome section of code. I have also included some other attempts that I have commented out. If it helps, this li ...

Using AngularJS: Implementing ng-include with a custom function

When using ng-include, I have encountered a peculiar issue. I am attempting to retrieve the template path by invoking a function defined in the controller that returns the path based on the parameter passed. Below is my code snippet: <tr ng-repeat="det ...

Use $.ajax to display the menu by capturing an array of elements {0}

Whenever I click on one of the DIV elements, a menu pops out on the side displaying more information about the clicked element. I can determine which element I'm clicking on, but I'm struggling to pass that information from jQuery to the PHP pag ...

Guide on updating the final element's value within an array and appending a new object into the array simultaneously using mongoose

"pmsStatus": [ { status: 0, fromTimeStamp: "12:40:50", reason: "no crane", toTimeStamp: "13:40:50" }, { status: 1, fromTimeStamp: &q ...