A guide on eliminating redundant sub-arrays consisting of both integers and strings from a two-dimensional array using Javascript

I have a 2-dimensional array that contains both integers and strings, and I'm looking to eliminate duplicates from it:

original array =

[["admin", 2, "regular"], ["customer", "regular"], ["regular", "customer"], [1], ,["admin"], [1], ["admin"]

desired outcome =

[["admin", 2, "regular"], ["customer", "regular"], [1], ["admin"]]

Can anyone suggest how I can achieve this using JavaScript?

Answer №1

Is it significant if the arrangement of your array (and its sub-arrays) changes? If not, then:

var arr = [["admin", 2, "regular"], ["customer", "regular"], ["regular", "customer"], [1],["admin"], [1], ["admin"]];

arr = arr.map(x => x.sort()).sort();

var uniqueArr = [];
uniqueArr.push(arr[0]);

for (var j = 1; j < arr.length; j++){
  if (JSON.stringify(arr[j]) != JSON.stringify(arr[j-1])){
      uniqueArr.push(arr[j]);
      }
}

console.log(uniqueArr);

Answer №2

One way to achieve uniqueness is by sorting a copy of the inner arrays, creating a string representation, and then comparing against a hash table while filtering.

var array = [["admin", 2, "regular"], ["customer", "regular"], ["regular", "customer"], [1], ["admin"], [1], , ["admin"]],
    object = Object.create(null),
    unique = array.filter(function (a) {
        var b = a.slice().sort().join('|');
        return !object[b] && (object[b] = true)
    });
    
console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

Check out this non-JavaScript algorithm that I came up with for you. It may not differentiate between ["customer", "regular"] and ["regular", "customer"], but it should give you a general idea:

var uniqueArray = [];
for(item in originalItems) { //iterate through the original array
    var isUnique = 1; //flag to check if item is already in uniqueArray
    for(existingItem in uniqueArray) {
        if(existingItem == item) isUnique = 0; //item is already in uniqueArray
    }
    if(isUnique == 1) uniqueArray += item; //add item if not already in uniqueArray
    isUnique = 1; //reset flag value
}

In essence, this logic helps you create a new array with only unique values. Good luck with your coding endeavors :)

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

Utilizing Ajax to fetch a div element from a web page

Hey there! I have a link set up that loads a page into a specific div ID, which is #ey_4col3. The issue I'm facing is that it loads the entire page along with all its contents, but what I really want to load from that page is just the content within ...

Encountering Type Error in Angular 2

Here is the Angular 2 code snippet I am working with: <ion-grid *ngFor="let item of menuData; let i = index;" ng-init="getAllItemToGrid()"> <img src="{{'assets/Products/'+menuData[i].image}}" ng-click="onLogin()" width="100%"> ...

What is the best way to automatically log out a user when a different user logs in on the same browser?

Currently, I am encountering an issue where there are two separate dashboards for different types of users - one for admin and the other for a merchant. The problem arises when an admin logs in on one tab and then a merchant logs in on another tab in the s ...

Array containing two objects in a two-dimensional format

In the example provided, I am working with a 2D array. Link to the example: https://codesandbox.io/s/v0019po127 I am noticing different results depending on whether I use the browser console or Codesandbox's console. I have attempted using JSON.str ...

Merge two flat arrays together based on their index positions to create an associative array with predefined keys

These are my two arrays: Array ( [0] => https://google.com/ [1] => https://bing.com/ ) Array ( [0] => Google [1] => Bing ) Here is the desired JSON output: [ { "url": "https://google.com/", ...

The YouTube video continues to play even after the container is closed

I recently worked on implementing a lightbox feature using jQuery, where a window opens upon clicking an element. Everything was working fine with images, but when I tried to open a YouTube video and play it, the video kept playing in the background even a ...

React: Improve performance by optimizing the use of useContext to prevent unnecessary re-renders of the entire app or efficiently share data between components without causing all

In my app, I have a Header.tsx component that needs to be accessible on all pages and a Home.tsx component where most of the content resides. The Home.tsx component includes an intersectionObserver that utilizes the useContext hook (called homeLinks) to p ...

The output of the http.get or http.request callback is only visible within the shell when using node.js

Just dipping my toes into node and aiming to avoid falling into the callback hell trap. I'm currently working with two files: routes.js fetch.js //routes.js var fetchController = require("../lib/mtl_fetcher/fetcher_controller"); var express = requir ...

Whenever I try to update my list of products, I encounter an error message stating that the property 'title' cannot be read because it is null

I am encountering an issue with editing data stored in the database. When attempting to edit the data, it is not displaying correctly and I am receiving a "cannot read property" error. HTML admin-products.component.html <p> <a routerLink="/ad ...

What could be causing the appearance of a mysterious grey box hovering in the upper left portion of my image and why is the code only adjusting the size of the grey box instead of the entire

I've been working on embedding some JavaScript into my Showit website to create a drag-and-drop feature that displays a collage/mood board effect. Everything is functioning correctly, but I'm running into issues with resizing the images. There&a ...

Converting XML attributes into arrays using PHP

Looking for a solution to parse XML with thousands of nodes and attributes into PHP arrays? Each node in the XML file contains various attributes like: <Class Option1="fiahfs;if" Option2="fiowfr0r0" ClassID="1"> <Class Option1="ro;ewaj;frwajro" O ...

Guide to building an HTML table using an array of objects

Is there a way to dynamically create a table from an array of objects? Here's an example array: let data = [{name: 'Player1',score:10}, {name: 'Player2',score: 7}, {name: 'Player3',score:3}] The desired HTML output shou ...

Search two arrays in a loop and identify variations with a unique approach

Currently, I am facing a challenge that I need assistance with. I am working on an updater that retrieves an XML list of files from a CDN and compares it with an older list to identify any file differences. The objective is to determine which files are out ...

Complications in C++ with Converting an Array into a List

I recently encountered an issue with some code from my programming class. Here is the function in question: void ToList(List *first, int *arr, int n) { List *p = first; for(int i=0; i<n; i++) { p->x = arr[i]; if (p->next != ...

The JQuery(document).ready function does not seem to be executing on the webpage, but it works as expected when placed in a

I have encountered a peculiar problem. It's strange to me because I can't figure out the root cause of it, despite trying everything in the Chrome Developer Tools debugger. Here is a snippet of code that works when I run it from a file on my desk ...

Learning how to access my CSS file using Express and Node.js

I am new to using express and node.js. I am trying to develop my app, but for some reason, my style.css file is not being recognized and I am unsure why. Initially, I attempted to use .scss files, but after researching, I discovered that it was not possi ...

What is the best way to change a byte array into a string?

Referencing the function found at: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx public static byte[] convertStringToBytes_AES(string plainText, byte[] Key, byte[] IV) In the original function, it returns a byt ...

Encountering an issue while trying to launch an Angular application on localhost. Vendor.js resource failed to load

Whenever I compile the code, it runs successfully. However, when I try to serve the application using 'node --max-old-space-size=8192', even though it compiles without any errors, when I open the app in a browser, it returns an error saying "Cann ...

Deciphering the functionality of req.flash()

I'm finding myself confused about how to use req.flash in node.js. For example, I have a .catch block that looks like this: Login function .catch(function(e){ req.flash('errors', 'error here') res.redirect('/') }) ...

Looking to replicate a Modal that I designed, but unsure which elements need altering in order to achieve this. I am hoping to create three duplicates of the Modal

This modal is functioning perfectly, and now I want to replicate the same modal three times on a single page. I require three distinct buttons on the same page to trigger these separate modals. At this point, I am unsure which attributes need modification ...