Creating unique identifiers for each level within a multidimensional array using JavaScript

I'm currently working on creating a list that contains all the distinct levels within a multidimensional array of objects.

Given this dataset...

let levels = [
  ["P", "B", "L"],
  ["A", "B", "L3"],
  ["A", "B", "L3"],
  ["P", "B", "M"],
  ["P", "C", "L"],
  ["A", "C", "L3"]
];

The desired output should be structured like this:

const result = [
  [1, 'P', 11, 'P.B', 111, 'P.B.L'],
  [1, 'P', 12, 'P.C', 121, 'P.C.L'],
  [2, 'A', 21, 'A.B', 211, 'A.B.L3']
];

Please note:

Each entry in the array represents a unique level.

Level identifiers: 
1 => Level 1 
11 => Level 1 and its sub-level
111 => Level 1, its sub-level, and the next level down

For each new Level 1, the identifier increments as follows for subsequent levels and their sub-levels:
2 => New Level 1
21 => New Level 1 and its sub-level
211 => New Level 1, its sub-level, and the sub-level's level

I am encountering difficulties in determining the level identifiers for each distinct pair. At this point, I have only managed to return the unique pairs as shown here:

function updateLevels(levels) {
  const { result } = levels.reduce(
    (acc, crr) => {
      const l1Key = crr[0];
      const l2Key = `${l1Key}.${crr[1]}`;
      const l3Key = `${l2Key}.${crr[2]}`;

      if (!acc.checkMap[l3Key]) {
        acc.checkMap[l3Key] = true;
        acc.result.push([l1Key, l2Key, l3Key]);
      }

      return acc;
    },
    {
      checkMap: {},
      result: [],
    }
  );
  return result;
}

const result = 
[
  ['P', 'P.B', 'P.B.L'],
  ['A', 'A.B', 'A.B.L3'],
  ['P', 'P.B', 'P.B.M'],
  ['P', 'P.C', 'P.C.L'],
  ['A', 'A.C', 'A.C.L3']
]

Answer №1

Here is a simple solution that involves two main steps:

  1. First, create an array that contains numbers and connected strings.

    You can use an object to store the level information and utilize a flag called add to determine when to add a new array to the result set.

  2. Next, sort the resulting array by selecting elements at odd indices.

const
    getUnique = array => {
        const levels = { _: 0, data: [] };
        
        return array
            .reduce((r, a) => {
                let add = false;
                const
                    temp = [],
                    final = a.reduce((l, v, i, a) => {
                        if (!l[v]) {
                            l[v] = {
                                _: 0,
                                data: [(l.data[0] || 0) * 10 + ++l._, (l.data[1] || '' ) + (l.data[1] ? '.' : '') + v]
                            };
                            add = true;
                        }
                        temp.push(...l[v].data);
                        return l[v];
                    }, levels);

                if (add) r.push(temp);

                return r;
            }, [])
            .sort((a, b) => {
                let i = 0, r = 0;
                while (i < a.length && !r) {
                    r = a[i] - b[i];
                    i += 2;
                }
                return r;
            });
    },
    levels = [["P", "B", "L"], ["A", "B", "L3"], ["A", "B", "L3"], ["P", "B", "M"], ["P", "C", "L"], ["A", "C", "L3"]],
    result = getUnique(levels);

result.forEach(a => console.log(...a));

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

Using an Array as an Argument in a JavaScript Function

Currently, I am utilizing a web service to populate a selection list. Now, I need to repeat this process for multiple selection lists, with the goal of minimizing the amount of code duplication. Below is the function I am using to make the web service call ...

The Jquery ajax get method is malfunctioning

I've been trying out this code but it doesn't seem to be working. Apologies for the basic question, but I'm curious to understand why it's not functioning as expected. $(document).ready(function(){ $("button").click(function(){ ...

js Display Type Error

Here is a snippet of JavaScript code that seems to be causing an issue: needSubIdCheck = $("#needSubIdCheck").text(); liveSupplierCount = $("#liveSupplierCount").text(); subIdCount = $("#subIdCount").text(); if(needSubIdC ...

What could be causing the embedded dropdown to automatically select the initial option every time?

I am encountering an issue with a page that includes an html table rendered using node with express and ejs. The table contains a select dropdown in one of the cells, and it populates correctly with the right values. However, regardless of which option I ...

What is the best way to swap out an HTML file with another without altering the link?

I'm working on an HTML file, which is basically a webpage. My goal is to create a functionality where clicking a button will dynamically replace the content of the page with another HTML file, complete with its own CSS, JavaScript functions, and other ...

In Firefox, using $().focus to target a textarea does not yield the intended results

Here is the problem recreated: http://jsfiddle.net/Rc52x/5/ In Chrome, when you click on Click here!, the textarea gains focus and allows typing. However, in Firefox (version 3.6.15), clicking on it does not give focus to the textarea and typing has no e ...

Maintaining form data while dynamically including more instances of a <div> element to the form

I am currently developing a SpringMVC Webapp with a view that contains a dynamic form. The dynamic elements of the form are listed below: At the moment, I am passing the variable ${worksiteCount} from my controller to the view (stored in my portlet sessio ...

Hitting a button causes Ajax.load to malfunction

Struggling to make ajax.load method work when clicking a button. The concept is simple: swap out the content of a div with something else using ajax.load. However, despite hours of research, I have yet to find a solution. Pressing the button does nothing. ...

Saving text as an array with: Mongoose, MongoDB, and SimpleDB-mongoose

Within my schema, I define the following: Links: [] When working with a post request in Node.js, my code looks like this: app.post('/add', function (req, res) { var newItem = new db.Item({ Links[0]: req.body.Link1 Links[1]: req.bo ...

Angular.js model that is updated by checkboxes

In my project, I have created a model that is linked to several other models. For instance, let's consider a scenario similar to a Stack Overflow question associated with tags. Before making a POST or PUT request, the final Object may appear like this ...

Using jQuery to define a variable with .attr method and subsequently modifying it

I am trying to work with multiple fields, some of which have corresponding labels: <input id="1" /><label for="1" /> <input id="2" /> <input id="3" /><label for="3" /> My goal is to retrieve the "for" attribute value from ea ...

React - Updating the document title upon user navigation away from the current page

I have encountered a challenge and I am seeking guidance on how to resolve it. Throughout our website, all pages have a default title based on our index.html file: <html lang="en"> <head> <title>My Page Title</title> ...

Sorting in Vuejs fails to function properly when a filter is applied

Having recently delved into Laravel and Vue, I am eager to develop a site for our Intranet. Pulling data from the Laravel database has been successful, displaying the data works well, and the search functionality is also up and running smoothly. However, I ...

Guide on creating a menu that remains open continuously through mouse hovering until the user chooses an option from the menu

I have a unique scenario where I am working with two images. When the mouse hovers over each image, two corresponding menu bars appear. However, the issue is that when the mouse moves away from the images, the menu disappears. Any suggestions on how to im ...

Create a JSON array containing two pieces of data

Can you please help me figure out how to retrieve the results for both 'content' and 'categories' values in the JSON array below? Currently, it only displays results for 'content'. $abc=$_GET["term"]; $query=mysql_query ...

Using JQuery to create interactive dropdown menus with dynamic options

I am exploring the possibility of dynamically updating the choices available in an HTML dropdown menu based on the selection made by a user - consider this sample JSON data: series: [ {name: 'Company X', product: 'X1'}, {name: 'Co ...

What could be causing NgModel to fail with mat-checkbox and radio buttons in Angular?

I am working with an array of booleans representing week days to determine which day is selected: selectedWeekDays: boolean[] = [true,true,true,true,true,true]; In my HTML file: <section> <h4>Choose your days:</h4> <mat-che ...

Guidelines for generating and printing a receipt on a thermal printer using react.js and NodeJs?

After creating an office application to manage a supermarket using Windev, my client now wants to enable remote access and control over the internet. To achieve this, I am considering transforming the application into a web application using React.js in th ...

What steps do I need to take in Bootstrap 5 to add a search icon to the navbar that reveals a search box beneath it when clicked?

I've made progress on the navbar design Now, I'm looking to add a search icon next to the login button. Clicking on the search icon should reveal a search box below the navbar, similar to the image shown below. My transparent navbar has a relati ...

I have been utilizing the library phonegap-nfc for scanning NFC tags, but I'm encountering an issue where instead of staying on the current

I have integrated the phonegap-nfc library into my vue project, and it is working fine. However, I am facing an issue where the information from my NFC card is being displayed on a different page instead of within my app. I want to show all the information ...