Utilizing Node.js to iterate through arrays grouped by categories

Here is some data I need to work with

[
  [ '@test','1.2.6-unstable' ],
  [ '@test','1.3.2-unstable' ],
  [ '@test','1.4.6-unstable' ],
  [ '@test2','4.0.1-unstable' ],
  [ '@test2','4.0.2-unstable' ],
  [ '@test2','4.0.3-unstable' ],
  [ '@test3','2.2.0-unstable' ],
  [ '@test3','2.2.3-unstable' ],
  [ '@test3','2.2.9-unstable' ],
...
]

I want to group them by the name @test, then iterate through the values and perform a task on each value in the new arrays, excluding the first value. The desired output should be

[
  [ '@test','1.3.2-unstable' ],
  [ '@test','1.4.6-unstable' ]
]
[
  [ '@test2','4.0.2-unstable' ],
  [ '@test2','4.0.3-unstable' ]
]
[
  [ '@test3','2.2.3-unstable' ],
  [ '@test3','2.2.9-unstable' ]
]

I have reviewed various resources but am struggling to find the right solution to achieve my goal
break array of objects into separate arrays based on a property
Can't loop over grouped array in JS
JS loop through array and group with map
I have also experimented with using .shift() and .slice(1) but they only remove the first element from the entire original array

Here is a snippet of my code:

const response = await axios.get(reportURL, { headers });
const mystuff = response.data.value.reduce((acc, next) => {
  acc.push(...next.versions.map((v) => [next.name, v.version]));
  return acc;
}, []);
const filteredArray = mystuff.filter(([_, version]) => version.includes('-unstable'));
const map = filteredArray.reduce((acc, { name, version }) => {
  if (acc.has(name)) {
    acc.get(name).versions.push(version);
  } else {
    acc.set(name, { name, versions: [version] });
  }
  return acc;
}, new Map());

const result = [...map.values()];

// Iterate through the array and make requests using axios
result.forEach(([name, version]) => {
  const URL = `https:URL/${name}/versions/${version}?api-version=7.1-preview.1`;

Answer №1

One approach is to group the nested arrays by their first item using the Object.groupBy method and then extract only the values from the groups.

After grouping, you can remove the first item from each group to get the desired result.

const
    data = [['@test','1.2.6-unstable'], [ '@test','1.3.2-unstable'], ['@test','1.4.6-unstable'], ['@test2','4.0.1-unstable'], ['@test2','4.0.2-unstable'], ['@test2','4.0.3-unstable'], ['@test3','2.2.0-unstable'], ['@test3','2.2.3-unstable'], ['@test3','2.2.9-unstable']],
    grouped = Object
        .values(Object.groupBy(data, ([first]) => first))
        .map(group => group.slice(1));

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

If you prefer a solution without using groupBy, you can achieve the same result by using a reduce function to group the arrays based on their first item.

const
    data = [['@test','1.2.6-unstable'], [ '@test','1.3.2-unstable'], ['@test','1.4.6-unstable'], ['@test2','4.0.1-unstable'], ['@test2','4.0.2-unstable'], ['@test2','4.0.3-unstable'], ['@test3','2.2.0-unstable'], ['@test3','2.2.3-unstable'], ['@test3','2.2.9-unstable']],
    grouped = Object.values(data.reduce((result, array) => {
        if (result[array[0]]) {
            result[array[0]].push(array);
        } else {
            result[array[0]] = [array];
        }
        return result;
    }, {}));

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Manipulating data in node.js as it arrives in separate chunks

Hey there, I am trying to make some changes to the data received from the server. All incoming data via the POST method is processed in chunks. <button id='helloButton'>Send hello!</button> <button id='whatsUpButton'>S ...

Switching between two states of a single 'td' element within a column

I am trying to implement a feature where only specific elements in the fourth column of a four-column table toggle when clicked. For example, clicking on an element in the fifth row third column should toggle the corresponding element in the fifth row four ...

Switch the header from left to right movement for mobile devices

I am dealing with two headers in my layout <section> <header class="col-lg-9"> <!-- some content --> </header> <header class="col-lg-3"> <!-- some content --> </header> </section ...

What is the best way to retrieve information from a JSON object?

Currently, I'm in the process of developing a Discord bot that will utilize commands from a JSON file. For example, if the command given is "abc", the program should search for "abc" in an array of commands and respond with the corresponding data. Bel ...

Having trouble with the Ng multiselect dropdown displaying empty options?

I'm currently facing a challenge in adding a multiselect dropdown feature to my project. Below is the code I have been working on: HTML <ng-multiselect-dropdown [settings]="searchSettings" [data]="dummyList" multiple> </n ...

Adjusting the width of innerHtml within a React router link to match the parent element's width

My current challenge involves a table where a cell is represented as a link. Within this setup, I am incorporating html content into the text of the link: <TableCell align="left" classes={{root: classes.cellPadding}}> <Link className={classes.l ...

Problem with AngularJS Multiselect checkbox dropdown configuration

In my application, I have a pop-up that includes a multi-select dropdown menu. Here is the code for the Multi-Select Dropdown: <select name="edit_tags" class="form-control" id="advisor_article_tagsx" multiple="" required ng-model="article_selected ...

The number of child notes can vary depending on the browser being used

Having an issue with a JavaScript function that is supposed to read an XML file. function readXML() { alert("readXML"); if(xmlDoc.readyState == 4 || xmlDoc.readyState == 'complete') { for(var i=0; i < xmlDoc.getElementsByT ...

From Google Assistant to Python Results

Is there a way to control a Bitcraze Crazyflie drone using Google Home? I'm looking to give the command "Drone fly to x3 y4" which will be processed through Firebase and result in the Google Assistant Output: "Flying to x3 y4". Additionally, I need an ...

Conceal the second click action within the anchor tag

Is there a way to hide the second click event on all anchor tags except those that trigger popupfun? I have a sample page set up. [Check out the JS Fiddle here][1] http://jsfiddle.net/ananth3087/LgLnpvf4/15/ Link Anchor Tags: The page includes two ...

How can I pass and use variables acquired in one function within a PHP foreach loop's iterations?

As I delve into learning PHP, I have been experimenting with dynamic data retrieval from XML and JSON files. In my exploration, I have created two separate codes to achieve different tasks. The first code pertains to fetching data from an XML games list, t ...

How can I use JQuery to enable or disable checkboxes upon loading?

I am looking to implement a feature where the checkboxes are enabled when the .group is checked and disabled when it is unchecked. Although I can toggle between them, I'm facing difficulty in disabling the unchecked checkbox using the .group. Upon lo ...

What is the best way to erase information displayed when hovering over an element using mouseout?

Whenever the user hovers over an image, an information box appears regarding that specific image. The information inside the box changes as I move over another image, but when not hovering over any images, the information box remains visible. Unfortunately ...

Error: Headers cannot be set once they have already been sent

My app.js file has the following code snippet: app.use(function(req, res, next){ if(!req.user){ return res.redirect('/login_'); } next(); }) Everything seems correct so far. In my route/index.js file, I have the following code: rout ...

Icon-enhanced Bootstrap dropdown selection

I have a unique select dropdown using Bootstrap where I want to display icons like the example below: https://i.sstatic.net/dZmTS.png <!DOCTYPE html> <html> <head> <script src="/scripts/snippet-javascript-console.min.js?v=1"& ...

Replace the foreach loop with a for loop

As a beginner in PHP, I have a question. How can I modify this foreach loop to only iterate twice? <?php foreach($results as $row): ?> ...

This element is not suitable for use as a JSX component since its return type 'void' is not a valid JSX element. Please check the return type to ensure it is compatible with

I have been working on this code snippet: function searchData(searchWord: any) { if (originalData.length > 0) { if (searchWord !== "") { setDataList([...originalData.filter((svc: any) => ...

Transitioning the existing application from iOS Cordova's UIWebView to WKWebView requires disabling asynchronous JavaScript execution in order to maintain functionality

Previously, in one of our older examples for saving data, we had successfully used the following code in cordova UIWebview without any issues: var filenameID; function getFilenameID() { $.ajax('/jquery/getdata', // request url { success ...

Creating an interactive map on an image using HTML and drawing circles

I've been experimenting with drawing circles on images using the map property in HTML. I have an image set up, and when clicking on the image in JavaScript, I'm adding the area coordinates for the map property. However, I keep encountering a null ...

Passing data from the server to the HTML page for manipulation

I need assistance in retrieving and manipulating the value stored in the variable $result[] from a PHP file to my HTML file for further processing. Can you provide guidance or reference code on how to return data from server side to client side? Here is a ...