Merging elements of an array

There is a single array that holds appointmentID (first value) and supperBillID (second value) separated by a comma. The AppointmentID will always be unique, but the superBillID can be repeated in consecutive positions. The goal is to create an array that groups all appointmentID values with the same billingID, separated by commas.

I have attempted to write the following code, but it is not producing the desired output:

var fg = ['10000021,23', '10000022,23', '10000023,24', '10000024,25', '10000025,25', '10000026,25', '10000027,26', '10000028,27'];
var tab = [];
var gbl = 0;

for (var i = 0; i < fg.length; i++, gbl++) {
    var vb = fg[gbl].split(',')[1]; // Will use try catch here
    var mainAr = fg[gbl].split(',')[0];

    for (var j = i + 1; j < fg.length; j++) {
        if (vb == fg[j].split(',')[1]) {
            mainAr = mainAr + ',' + fg[j].split(',')[0];
            gbl++;
        }
        else {
            break;
        }
        tab.push(mainAr, vb);
    }
}

Sample Input:

var input = ['10000021,23', '10000022,23', '10000023,24', '10000024,25', '10000025,25', '10000026,25', '10000027,26', '10000028,27'];

Expected Output:

output = ['10000021,10000023',23]
         ['10000023',24]
         ['10000024,10000025,10000026',25]
         ['10000027',26]
         ['10000028',27]

Answer №1

If you're looking to organize the appointmentID values and avoid duplicates using billingID as the key, you can start by utilizing Array.reduce() to group them into a Set.

Then, you can further refine the structure using Array.map() on the object generated, depending on the desired output format. You can choose between an array of arrays or an array of strings resembling the input style.

var input = ['10000021,23', '10000022,23', '10000023,24', '10000024,25', '10000025,25', '10000026,25', '10000027,26', '10000028,27'];

let output = input.reduce((acc, str) =>
{
    const [appointmentID, billingID] = str.split(",");
    acc[billingID] = acc[billingID] || new Set();
    acc[billingID].add(appointmentID);
    return acc;
}, {});

// Transform to array of arrays:
let out1 = Object.entries(output).map(([k, v]) => [[...v].join(","), +k]);
console.log("Array of arrays", out1);

// Transform to array of strings:
let out2 = Object.entries(output).map(([k, v]) => [...v, k].join(","));
console.log("Array of strings", out2);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Another approach, considering unique AppointmentID and potential repetition of superBillID in consecutive positions, could be:

var input = ['10000021,23', '10000022,23', '10000023,24', '10000024,25', '10000025,25', '10000026,25', '10000027,26', '10000028,27'];
let output = [];

for (let i = 0; i < input.length; i++)
{
    const [appointmentID, billingID] = input[i].split(",");
    const len = output.length - 1;

    if (output[len] && output[len][1] === +billingID)
        output[len][0] += "," + appointmentID;
    else
        output.push([appointmentID, +billingID]);
}

console.log(output);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Answer №2

To condense the array, you can utilize the reduce method by treating each supperBillID as a key in the accumulator. Update the 0 index if the supperBillID already exists, otherwise add the key to the accumulator and assign it to an array. Extract the values as an array with the help of Object.values()

var fg = ['10000021,23', '10000022,23', '10000023,24', '10000024,25', '10000025,25', '10000026,25', '10000027,26', '10000028,27'];

const merged = fg.reduce((acc, o) => {
  const [appId, billId] = o.split(',');
  if (acc[billId])
    acc[billId][0] += `,${appId}`;
  else
    acc[billId] = [appId, billId]
  return acc;
}, {})

const output = Object.values(merged);

console.log(output)

Answer №3

Begin by transforming the array into a more manageable array of objects, then proceed to condense the array based on the specified condition

const input = [
  "10000021,23",
  "10000022,23",
  "10000023,24",
  "10000024,25",
  "10000025,25",
  "10000026,25",
  "10000027,26",
  "10000028,27"
];

const dataset = input.map(item => {
  const nodes = item.split(",");

  return {
    appointmentid: nodes[0],
    superbillid: nodes[1]
  };
});

const output = dataset.reduce((accumulator, current) => {
  const item = accumulator.find(
    element => element[element.length - 1] === current.superbillid
  );

  if (item !== undefined) {
    item.unshift(current.appointmentid);
  } else {
    accumulator.push([current.appointmentid, current.superbillid]);
  }

  return accumulator;
}, []);

console.log(output);

If you want to obtain an array of strings, you can achieve this by using the map function on each item in the array like so

const recipient = output.map(item => item.join(',')));

This operation will result in

[
  "10000022,10000021,23",
  "10000023,24",
  "10000026,10000025,10000024,25",
  "10000027,26",
  "10000028,27"
]

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

Making if-else statements easier

Greetings! I have a JSON data that looks like this: { "details": { "data1": { "monthToDate":1000, "firstLastMonth":"December", "firstLa ...

What is the best way to extract clean text from HTML using JavaScript?

I am struggling with the code below in my HTML file: function hideContent(){ // Need help with this part! } <input type="button" onclick="hideContent()" value="Hide Content"/> <p id='txt'> <span class="A">I am</span> ...

Enhance state using the values from radio buttons in a React application

Seeking the best approach to update or set my state that stores values for radio button answers. This pertains to a personality test with 20 questions, and I aim to store all 20 answers. Each radio button input has an onChange event. My objective is to st ...

Retrieving Data from Outside Source using AngularJS

Is there a way to retrieve JSON-Text-Stream data from a specific URL (e.g. SOMEURL/ean.php?id=4001513007704)? The returned result typically appears as follows: { "product": { "ean_id": "4001513007704", "title": "Gerolsteiner Mineralw ...

What is the best way to outline the specifications for a component?

I am currently working on a TypeScript component. component @customElement("my-component") export class MyComponent extends LitElement { @property({type: String}) myProperty = "" render() { return html`<p>my-component& ...

Finding the Perfect Placement for an Element in Relation to its Companion

Is there a way to achieve an effect similar to Position Relative in CSS using jQuery? I have developed a tooltip that I want to attach to various objects like textboxes, checkboxes, and other text elements. My code looks something like this: <input i ...

Is the Webpack vendors JS bundle in Vue CLI containing unlisted code that is not in the dependencies or package-lock.json file?

An information security auditing tool flagged an outdated library with known vulnerabilities in our webpack-bundled chunk-vendors.js file generated using Vue CLI: The library in question is YUI 2.9.0. It appears that this library is not fully included, a ...

Engaging JavaScript Navigation

I am looking to create an interactive JavaScript menu or image map where users can press down, highlight, and hit enter on four different items to reveal hidden messages. However, I struggle with JavaScript and could really use some assistance. I have alr ...

Issue with custom function not being triggered by datepicker onSelect in Internet Explorer with JQuery

I have a datepicker set up like this: $("#startDate").datepicker({ onSelect: changeDate }); This is used with the following input field: <input type="text" id="startDate" value="" class="dateField"/> This setup works well in Chrome, but encou ...

Acquire feedback from PHP using SweetAlert notifications

I need to update my HTML form to function like this: <script> function getName() { var name = $('#name').val(); var url_send = 'send.php'; $.ajax({ url: url_send, data: 'name=' + name, ...

Double the fun: JavaScript array appears twice!

I am currently working on displaying the selected filters from checkboxes. Initially, I create an array containing the values selected from the checkboxes and then aim to add them to a string. Suppose I have two checkboxes labeled: label1 and label2, my a ...

I am looking to download a file from a server and showcase it in a browser using React.js. The file will be received as a response from the

**I am looking to retrieve a file from the server by sending the file name through the body and then receiving the requested file from the server.** I have successfully received the file in response from the server, which I tested using Postman. What I a ...

PHP - retrieve a one-dimensional array from a key-value paired array

I have an array that contains different elements, and I need to extract all the values that come before the 'id' key and store them in a separate array. For example: arry('12', '10', '11', '9') [ ...

Can you explain the concept of asynchronous in the context of Ajax?

Can you explain the concept of Asynchronous in Ajax? Additionally, how does Ajax determine when to retrieve data without constantly polling the server? ...

The back button stops working following the execution of window.location.replace(href);

A simple function I created allows all containers to behave like links with the click of a button. function allHot(element){ $(element) .click( function(){ var href = $(this).find('a').attr('href'); window.location.replace(h ...

Tips on running jQuery scripts when a div changes its display style from none to block?

Is there a way to trigger jQuery code when the style of a div transitions from `display: none;` to `display: block;`? I am working with tabs, which is why this div's style changes in this manner. The jQuery code should only be executed when this spec ...

Alignment of Material-UI dialogue buttons on the left side

I have a Dialog containing three buttons as shown below: https://i.stack.imgur.com/T6o35.png Here is the JSX code: <DialogActions classes={{ root: this.props.classes.dialogActionsRoot }} > <Button classes={{ root: this.props ...

Analog Clock Time Adjustment Bubble Deviation Dilemma

Recently, I encountered an issue with an analog clock component. Every time I click on the time adjustment bubble repeatedly while also moving the cursor position, it tends to drift away from its original placement, which should ideally be between an orang ...

Cookies in Node.js Express are not being incorporated

Currently, I am in the process of developing a nodejs application and facing an issue with defining cookies. Here is a snippet of the code that I am working with: var app = express(); app.set('port', process.env.PORT || 3000); app.set('vie ...

Utilize the inherited background color for a linear-gradient effect

Here is the code snippet I am working with: <label className={classes.trigger} htmlFor={uniqueId} ref={labelRef} style={{ background: val, borderColor: val }} /> This is the corresponding CSS: .trigger { display: block; posit ...