Searching an array in Javascript to dynamically create a table based on another array

I have two arrays in JavaScript that I need to combine into a table.

First Array:

[ 
{ route: 'x1' },
{ route: 'x2' },
{ route: 'x3' },
{ route: 'x4' },
{ route: 'x5' }
]

Second Array:

[ 
{ pattern: 'y1', route: 'x1' },
{ pattern: 'y2', route: 'x1' },
{ pattern: 'y3', route: 'x2' },
{ pattern: 'y4', route: 'x2' },
{ pattern: 'y5', route: 'x3' },
{ pattern: 'y6', route: 'x3' },
{ pattern: 'y7', route: 'x4' },
{ pattern: 'y8', route: 'x4' },
{ pattern: 'y9', route: 'x5' },
{ pattern: 'y10', route: 'x5' }
]

The desired table layout is as follows:

ROUTE PATTERN(s)
x1 y1, y2
x2 y3, y4
x3 y5, y6
x4 y7, y8
x5 y9, y10

I have the code working to generate both arrays from API calls. I also have a function to search for patterns based on a specific route in the second array.

function search(nameKey, myArray){ for (var i=0; i < myArray.length; i++) { if (myArray[i].route === nameKey) { return myArray[i]; } } } var resultObject = search("x1", array2); console.log(resultObject);

The HTML table for the first array looks like this:

{{#each array1}} {{/each}}
Routes and Corresponding Parts
ROUTE
{{this.route}}

I am struggling with creating a function that can match each object in the first array with the corresponding patterns in the second array dynamically.

Any help in simplifying the HTML code by achieving this would be greatly appreciated!

An ideal HTML structure would be:

{{#each array1}} {{/each}} {{#each queryarray2}} {{/each}}
Routes and Corresponding Parts
ROUTE
{{this.route}}{{this.matchedpatterns}}

Answer №1

Here's a simple way to achieve this:

let arr1 = [ 
{ route: 'x1' },
{ route: 'x2' },
{ route: 'x3' },
{ route: 'x4' },
{ route: 'x5' }
]


let arr2 = [ 
{ pattern: 'y1', route: 'x1' },
{ pattern: 'y2', route: 'x1' },
{ pattern: 'y3', route: 'x2' },
{ pattern: 'y4', route: 'x2' },
{ pattern: 'y5', route: 'x3' },
{ pattern: 'y6', route: 'x3' },
{ pattern: 'y7', route: 'x4' },
{ pattern: 'y8', route: 'x4' },
{ pattern: 'y9', route: 'x5' },
{ pattern: 'y10', route: 'x5' }
]

let result = arr2.reduce((a, b)=> {
  a[b.route] = a[b.route] || [];
  a[b.route].push(b.pattern);
  return a;
}, {});

console.log(result);

This code creates an object where the keys are routes and the values are arrays of patterns associated with each route.

Answer №2

After some tinkering, I managed to make everything function according to my needs, opting for a flatter combination rather than relying on the key/array pairing.

let arr1 = [{
        route: 'x1'
    },
    {
        route: 'x2'
    },
    {
        route: 'x3'
    },
    {
        route: 'x4'
    },
    {
        route: 'x5'
    }
]


let arr2 = [{
        pattern: 'y1',
        route: 'x1'
    },
    {
        pattern: 'y2',
        route: 'x1'
    },
    {
        pattern: 'y3',
        route: 'x2'
    },
    {
        pattern: 'y4',
        route: 'x2'
    },
    {
        pattern: 'y5',
        route: 'x3'
    },
    {
        pattern: 'y6',
        route: 'x3'
    },
    {
        pattern: 'y7',
        route: 'x4'
    },
    {
        pattern: 'y8',
        route: 'x4'
    },
    {
        pattern: 'y9',
        route: 'x5'
    },
    {
        pattern: 'y10',
        route: 'x5'
    }
]

routes = new Map,
result = arr1.map(o => (routes.set(o.route, {}), Object.assign(routes.get(o.route), o, { pattern: [] })));
arr2.forEach(o => routes.get(o.route).pattern.push(o.pattern));

console.log(result);

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

Enhancing the Syntax of If and If Else in Jquery Functions

I'm struggling to simplify and optimize this block of code. Would appreciate any help in making it more efficient! var status = "closed"; $(document).on('click', '[data-toggle-nav]', function(event) { if ($(this) && status = ...

Exploring the realms of object-oriented programming with JavaScript, jQuery, and AJAX

Here is the code snippet I am working with: var Foo = function(){ this._temp="uh"; }; Foo.prototype._handler=function(data, textStatus){ alert(this._temp); } Foo.prototype.run=function(){ $.ajax({ url: '....', succ ...

Angular 2 encountered a fatal error: Issues with parsing the template:

Here is the code snippet I am currently working with: <div class="container"> <div [hidden]="loggedIn"> <md-grid-list cols="6" [style.margin-top]="'20px'"> <md-grid-tile [colspan]="1"></md-grid-tile> I have already ...

Is it considered good practice to utilize Vue.js for managing global shared state and implementing for loops outside of components?

Just getting started with Vue.JS and experimenting with creating two lists of books (read and unread) from a shared object in the global data state. This is my approach - working demo (works like a charm! However, I'm wondering if this is considered ...

Issue of flickering/flashing in Next js when using conditional rendering

I've been attempting to implement localstorage for storing authentication with Next.js. I am using conditional rendering to ensure that localstorage is accessible before displaying the content. However, I am facing an issue where the page flickers or ...

Tips for extracting the two characters following a space in a string with or without the use of regex

How can I extract only the initials of 2 characters after spaces? See the code snippet below: const name = "John Peter Don"; const result = name.match(/\b(\w)/g).join(''); console.log(result)// JPD->> i want only JP ...

Over time, the server's connection to MongoDB weakens until it eventually fails to connect completely

Greetings to everyone! I trust you are all having a wonderful day. Last week, I sought assistance here in changing my app.js file to server.js, and the support I received was invaluable. However, I am back with a new issue that seems to have stemmed from t ...

Tips for preventing nested subscriptions from exceeding two levels

I have four subscriptions that depend on each other. While there are numerous suggestions on avoiding nested subscriptions, they often don't address more than two levels of nesting. How can I prevent so many nested subscriptions? This is the code fo ...

Encountered a cross-domain error with node.js and jQuery: ERR_CONNECTION_REFUSED

Just beginning my journey with Node.js. I've set up a basic node/express application that serves a single webpage featuring a button. When clicked, this button triggers a jQuery ajax request to an Express route. The route callback then makes an http ...

React scroll not triggering class changes

In the function handleScroll, I am attempting to add a class of red when scrolling down to a specific limit, otherwise applying a class of blue. However, it seems that it is only entering the else statement and also logging undefined for e.target.scrollTop ...

Seeking guidance on waiting for chrome.storage.sync.get after adding a listener in Chrome

My extension has been successfully modifying some URLs. However, I now need to determine whether the modification feature is enabled in the settings. chrome.webRequest.onBeforeRequest.addListener ( modifyUrl, {urls: ['http://somewebsite/*&apo ...

Getting the dimensions of an image using a path in JavaScript

I am trying to display a div with an image, its name, size, and download link using jQuery. Here is the code I have created: var image = 'image/example.png' $('#download').attr("href", result2); $('.image').attr("src", re ...

When attempting to generate a 2D array of a struct, it causes the system to crash

I'm facing an issue where my attempt to create a two-dimensional array of a struct leads to the program failing to launch. The program freezes and eventually quits after a few seconds. Can anyone provide insight into what may be causing this? Below i ...

Implementation of arrays with dynamic textboxes insertion

Looking for a dynamic array output like this: tableNames = [ ["string1", "string2"...], ["string", "string"...] ]; Looking for assistance with AngularJS code design to achieve this structure, where the values of the strings are entered through te ...

Exploring the Depths of MongoDB Arrays

Below is the structure of my MongoDB data: { "_id": "QEvgJKERy5xGNLv7J", "title": "test 2", "owner": "HQNGYZvrrdQRwLNvT", "markdown": "sdfasdfdasf adsfadsfasdf", "state": "Draft", "category": [ "Bios & Memoirs", "Classics" ], " ...

Updating Error: Unable to establish connection with IP address 104.16.21.35 on port 80; Error code: ECONNREFUSED. This issue is being handled by the _

I need help updating my Angular version from 5 to 6 and I'm following these steps: Want to upgrade project from Angular v5 to Angular v6 After running the commands ng update @angular/cli and ng update @angular/core, I encountered the err ...

How to determine if a radio button has been selected using Javascript?

I have come across scripts that address this issue, however they are only effective for a single radio button name. My case involves 5 different sets of radio buttons. I attempted to check if it is selected upon form submit. if(document.getElementById(&ap ...

Embracing AngularStrap's Popover Feature

I am attempting to create a custom directive that wraps angular strap's popover functionality. The goal is for the popover to be able to utilize a custom template provided by the user of my directive, and for the template to access the controller&apo ...

Access numerical values from JSON objects using JavaScript

I need assistance with implementing a JavaScript function to retrieve data from a JSON file and then display it on my webpage. The goal is to iterate through the values in a while loop and dynamically insert them into specific HTML elements. xhttp.onrea ...

Issue 404: Trouble sending form data from React to Express

I'm facing an issue when trying to send form data from a React frontend to my Node.js/Express backend. The problem seems to be related to a 404 error. I've included only the relevant code snippets below for reference. Function for submitting the ...