Combining two or more arrays containing similar values into a single array

Within my array, there are 100 subarrays, each containing 3160 values of an object with two attributes: a sequence number (which only appears if it is present as 1), and another value of either 0 or 1.

My goal is to merge all 100 arrays into one single array consisting of 3160 values of an object. This new array should have a list of all the sequence numbers found in the original arrays, along with the total sum of all the 0s and 1s combined.

I attempted to use concatenation, but I want to ensure that the final array does not exceed 3160 entries.

/* Current structure of my data:
  Array(100)
    [0]Array(3160)
      [0]: Seq: 12345
           fq: 1
      [1]: Seq: 12345
           fq: 0
      [2]: Seq: 12345
           fq: 1
      [3]: Seq: 12345
           fq: 0
      ...and so on...
    [1]Array(3160)
      [0]: Seq: 12346
           fq: 1
      [1]: Seq: 12346
           fq: 1
      [2]: Seq: 12346
           fq: 0
      [3]: Seq: 12346
           fq: 0
      ...and so on...
    [2]Array(3160)
      [0]: Seq: 12347
           fq: 1
      [1]: Seq: 12347
           fq: 0
      [2]: Seq: 12347
           fq: 1
      [3]: Seq: 12347
           fq: 0
      ...and so on...
    ...and so on...


Desired Output:
    Array(3160)
      [0]: Seq: 12345, 12346, 12347
           fq: 3
      [1]: Seq: 12346
           fq: 1
      [2]: Seq: 12345, 12347
           fq: 2
      [3]: Seq: 
           fq: 0
*/

Answer №1

After considering your feedback, it seems like you are interested in an approach similar to the one outlined below:

let data = [[{ID: 12345, count: 1}, {ID: 12345, count: 0}],
             [{ID: 12346, count: 1}, {ID: 12346, count: 1}],
             [{ID: 12346, count: 1}, {ID: 12346, count: 1}],
             [{ID: 12347, count: 1}, {ID: 12347, count: 0}]];

let result = new Array();
             

data.forEach(entries => entries.forEach((object, ind) => {
  if(object.count) {
    result[ind] = result[ind] || {ID: [], count: 0};
    if(!result[ind].ID.includes(object.ID)) result[ind].ID.push(object.ID);
    result[ind].count += object.count;
  }
}));

console.log(result);

Given that this solution deviates slightly from what was initially requested, I have opted to provide a fresh answer rather than modifying the original response.

Answer №2

Here is a JavaScript code snippet that manipulates an array of objects:

let array = [[{Seq: 12345, fq: 1}, {Seq: 12345, fq: 0}],
             [{Seq: 12346, fq: 1}, {Seq: 12346, fq: 1}],
             [{Seq: 12347, fq: 1}, {Seq: 12347, fq: 0}]];

let output = new Array();
             

array.forEach(entrie => entrie.forEach((obj, index) => {
  if(obj.fq) {
    output[index] = output[index] || {Seq: [], fq: 0};
    output[index].Seq.push(obj.Seq);
    output[index].fq += obj.fq;
  }
}));

console.log(output);

Answer №3

If you were to loop through the array and create new elements at the same index as the provided inner arrays, you could achieve a desired outcome.

var data = [[{ Seq: 12345, fq: 1 }, { Seq: 12345, fq: 0 }, { Seq: 12345, fq: 1 }, { Seq: 12345, fq: 0 }], [{ Seq: 12346, fq: 1 }, { Seq: 12346, fq: 1 }, { Seq: 12346, fq: 0 }, { Seq: 12346, fq: 0 }], [{ Seq: 12347, fq: 1 }, { Seq: 12347, fq: 0 }, { Seq: 12347, fq: 1 }, { Seq: 12347, fq: 0 }]],
    result = data.reduce((r, a) => {
        a.forEach(({ Seq, fq }, i) => {
            if (!fq) return;
            r[i] = r[i] || { Seq: [], fq: 0 };
            r[i].Seq.push(Seq);
            r[i].fq++;
        });
        return r;
    }, []);

console.log(result);
.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

Creating markers from Mysql database is a simple and efficient process

On my website, I have an array of markers that I use to display locations on a Google map. The array format I currently use is: generateMarkers([['Location', lat, long], ['Location2', lat2, long2],['Location3', lat3, long]3]) ...

Is there a way to obtain an array after subscribing to an RxJS method?

I am struggling with the following code snippet: Rx.Observable.from([1,2,3,4,5,6]) .subscribe(x=>console.log(x)); Is there a way to modify this code so that instead of iterating through the array elements from the .from() method, I can return the enti ...

Restricting the type of user input in HTML forms

Requirements: Input must be a whole number between 2 and 99, inclusive. Current Solution: <input required type="number" min="2" max="99" oninput="this.value = Math.abs(this.value)" maxLength="2" matInp ...

Difficulty displaying data from PapaParse in VueJS despite successful retrieval in console

My first attempt at using PapaParse is running into some issues. I am successfully parsing a remote CSV file and storing the data, as confirmed by console.log. However, when I try to output it with a v-for loop, nothing seems to be working. To achieve thi ...

Is there a clear definition of behavior when using non-Promise values with Promise.all?

Are the behavior of Promise.all() docs guaranteed in Node when non-Promise values are passed? For example, using Node 6.10.2: Promise.all([1, 2, 3]).then( res => console.log(res) ); In this scenario, it prints [ 1, 2, 3 ], but is it sure that Promis ...

Press the 'enter' button to post your tweet with Greasemonkey

I am working on a Greasemonkey script that will automatically submit a tweet when the user presses the 'enter' key. The script works perfectly on a basic HTML page with some help from tips I found on this website. However, when I attempt to use t ...

Iterating through textboxes and buttons to trigger actions in JavaScript

Having an issue with JavaScript (or jQuery) where I can successfully input text and click a button on a page using the following script: document.getElementsByName('code')[0].value='ads0mx0'; document.getElementsByName('event&a ...

Securing Email and Password Data in Cypress Tests

Greetings! I trust everyone is in good spirits. My dilemma lies in the fact that I am hesitant to include email and passwords in version control. I am considering using environment variables in my cypress tests and utilizing secrets for runtime value pro ...

Unable to locate the module '/workspace/mySQL/node_modules/faker/index.js'

Hi there, I'm currently facing an issue while trying to run the app.js file in my project through the terminal. It keeps showing me an error message that I am unable to resolve. To provide some context, I have already installed the faker package using ...

How can I intercept/manage the back button of the browser in React-router?

Utilizing Material-ui's Tabs, which are controlled, I am implementing them for (React-router) Links in the following manner: <Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/> <Tab value={1} label="users ...

Determine whether there is only one array in the object that contains values

At the moment, I am attempting to examine an array in order to determine if only one of its elements contains data. Consider this sample array: playersByGender = { mens: [], womens: [], other: [] }; Any combination of these elements may contain dat ...

AngularJS Splice Function Used to Remove Selected Items from List

I previously inquired about a method to remove items from the Grid and received a solution involving the Filter method. However, I am specifically looking for a way to remove items using the Splice Function instead. You can find my original question here: ...

Issue regarding navigation using nuxt-links to pages with hashtags/anchors

When it comes to my website navigation, I rely on nuxt-links a lot. Most of these links direct users to specific sections within the home page using hashes like: <nuxt-link v-else class="text-link" :to="localePath('index') + #hash" > ...

Loading indicator for buttons

Issue with submit button onclick function (onClick="mandatoryNotes()"). It is taking a while to load, so a preloader script was added. The preloader is now working, but the function is not being called. Seeking assistance. Thank you. function mandatoryN ...

The error message says: "VueComponent.filterKategori function cannot read property 'filter' because it is undefined at line 16260 in app.js."

this is the code snippet that I'm dealing with: computed: { filterKategori() { var kategori = this.kategori.data.filter(f => { return f.induk == null && f.id_klasifikasi == this.id_klasifikasi; }); return kat ...

Ways to utilize a single HTML page for various URLs while changing one variable value based on the queried URL

My current HTML page structure looks like this: <body ng-controller="DashboardDisplay" onload="submit()"> <div class="container-fluid" > {{scope.arr}} </div> </body> <script> var myApp = angular.module(&apos ...

Custom Joi middleware in Express v4 is failing to pass the Request, Response, and Next objects

I am currently in the process of developing a unique middleware function to work with Joi that will be placed on my routes for validating a Joi schema. In the past, I have created middlewares for JWT validation without passing any parameters, and they wor ...

Does turning off javascript in a browser impact ajax requests and javascript functions?

My mind is troubled I've been thinking of options like turning off JavaScript in the browser. If I do that, then AJAX and JavaScript functions won't work, right? If so, is there a solution? ...

Transfer information using cURL without the need to refresh the webpage

I am trying to send data to an external API using cURL from a Facebook iframe page (not tab). However, I want to achieve this without reloading the form page. My idea is to use jQuery AJAX to display a "submitting data" message upon form submission and sh ...

"Exploring the capabilities of Rxjs ReplaySubject and its usage with the

Is it possible to utilize the pairwise() method with a ReplaySubject instead of a BehaviorSubject when working with the first emitted value? Typically, with a BehaviorSubject, I can set the initial value in the constructor allowing pairwise() to function ...