Merging components from two multi-dimensional arrays in JavaScript

In my JavaScript code, I am working with two arrays:

"total":[[1370923200000,"66"],[1371009600000,"42"],[1371096000000,"23"]]

"successful":[[1370923200000,"5"],[1371096000000,"2"],[1371182400000,"0"]]

My goal is to merge these two arrays into a single array or object that looks like this:

{date:1370923200000, total:"66", successful:"5"},
{date:1371009600000, total:"42"},
{date:1371096000000, total:"23", successful:"2"},
{date:1371182400000, successful:"0"}

I have attempted various approaches to achieve this by iterating through both arrays, but I'm struggling to find an efficient solution.

Answer №1

Below is the code snippet:

var total = [[1370923200000, "66"],[1371009600000, "42"],[1371096000000, "23"]];
var successful = [[1370923200000, "5"],[1371096000000, "2"],[1371182400000, "0"]];
var combined = {};

for(var i=0; i<total.length; i++){
    combined[total[i][0]] = {date: total[i][0], total: total[i][1]};
}

for(var i=0; i<successful.length; i++){
    if(successful[i][0] in combined){
        combined[successful[i][0]].successful = successful[i][1];
    }
    else{
        combined[successful[i][0]] = {
            date: successful[i][0], successful: successful[i][1]
        };
    }
}

var result = [];
for(var key in combined){
    result.push(combined[key]);
}
alert(result.toSource());

Check out this functional demo http://jsfiddle.net/eRjeZ/

Answer №2

Here is a straightforward approach for handling n arrays:

var arrays = {"total":[…], "successful":[…]};

var result = [];
for (var prop in arrays) {
    var arr = arrays[prop];
    var i=0;
    for (var j=0; j<arr.length; j++) {
        var date = arr[j][0];
        while (i < result.length && date > result[i].date) i++;
        if (i < result.length && date == result[i].date) {
            result[i][prop] = arr[j][1];
        } else {
            var o = {date:date};
            o[prop] = arr[j][1];
            result.splice(i, 0, o);
        }
    }
}

If you're looking for improved performance, consider implementing the Multiple Array Merge Using Binary Heap technique (also check out Algorithm for N-way merge). For scenarios with just two lists, explore the options presented in Most efficient way to merge two arrays of objects.

Answer №3

let allData = [[1370923200000, "66"],[1371009600000, "42"],[1371096000000, "23"]];
let successData = [[1370923200000, "5"],[1371096000000, "2"],[1371182400000, "0"]];
let combinedData = {}; 
let finalOutput = [];

allData.map(  function( item ){ addToCombinedData( item , "total" ) } );
successData.map( function( item ){ addToCombinedData( item , "successful" ) } );

console.log( combinedData ); // This resembles the desired output

for( let key in combinedData )
  finalOutput.push( combinedData[key] );

console.log( finalOutput ); // Final result as expected

function addToCombinedData( item , name )
{
  let key = item[0];
  let entry = combinedData[key] || { date : key };
  entry[name] = item[1];
  combinedData[key] = entry; 
}

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

`Is it possible to retrieve numerous downloaded images from formData using Express for recovery purposes?`

Apologies for my English, I am facing a small issue. I am attempting to upload multiple images but on the backend, only one image is being displayed. I am using React, Express, Formidable, and Cloudinary. Below is my front-end code: const [arrayFiles, set ...

The XHR request fails to transmit a JSON object

Having a client-server express app, I am currently working on sending an XHR request from my frontend to the controller while passing JSON data. The code snippet from my frontend looks like this: function handle_login(){ var username_field = document. ...

In configuring the print settings, I specified margins to ensure proper formatting. However, I noticed that the margin adjustment only applies to the first page. I need

I have a method that retrieves margin top value from the backend. It works perfectly on the first page of print, but on the second page, the margin top space is missing. initializePrintingSettings() { this.printService.fetchPrintSettings().subscribe(respon ...

Set the value obtained from a resolved promise to a mutable reference object in a React component

I am in the process of developing a random movie generator. I am utilizing an external API to retrieve a list of movies and then selecting one randomly from the returned data. The current implementation is as follows: export default function Page() { con ...

Update JavaScript files by utilizing a different JavaScript document

Is it possible to modify a JSON object within a JS file using another JS file? For instance, let's consider the JS file that needs editing (eslintrc.js): module.exports = { root: true, parserOptions: { parser: 'babel-eslint', ...

Delete the designated column from the table

I am having difficulty with hiding and showing table columns using checkboxes. I need to eliminate the Mars column (in bold) along with its corresponding data (also in bold). Once the Mars column is removed, I want the Venus column and its data values to ...

Would it be considered safe to make a reference to an array element that is out of bounds if the reference is not used at all?

As I delve into an API, the task at hand involves the caller passing an array of pointers to various items along with the array's length. To enhance the readability and maintainability of my code, I aim to assign names to each argument rather than sim ...

Struggling with the development of a crossfading image gallery using jQuery's .animate() function while ensuring compatibility with IE8

Seeking assistance in creating a crossfading image gallery using jQuery and the .animate() function. I'm struggling to solve the issue of smooth fadeIn for the next image while maintaining compatibility with IE8. https://jsfiddle.net/Vimpil/fqhc1e9m/ ...

What is the reason that when a <div> click on a mobile device includes a jQuery ('#item').fadeOut() function, the CSS of the '#item' element maintains its previous hover state

While creating a mock back to top button, I encountered an issue with my jQuery call to fadeOut() behaving differently on mobile devices (this discrepancy can be observed using any desktop browser simulator). You can find the source code here: https://cod ...

JavaScript code for displaying mouse positions and Geolocation using OpenLayers, along with a Geocodezip demonstration

I have attempted to merge Geolocation and Mouse Position Display (longitude/latitude; outside of map) from the OpenLayers and geocodezip site, but I am facing issues. The Mouse Position Display works correctly, however, Geolocation does not seem to work. U ...

"Utilize gulp-connect to store the root as an array

The gulp-connect documentation mentions that options.root can accept either an array or string. My situation involves having a build directory that I want to use as the root, along with a separate sources directory where all my source maps are located. Is ...

Angular router.redirect is not able to pass variables as expected

I am facing an issue with the router redirect and template lifecycle while using Stripe checkout in my Angular 5 project. After a user signs up, I trigger the stripe checkout modal. Once the modal receives a payment source token, I perform some additional ...

How to achieve a one-time use of JQuery scrollTo for scrolling to a specific

Currently, I am in the process of developing a website where I showcase my child pages using a slideshow on the main parent page. Each child page has a scroll down link that should smoothly transition to the first title above the image when clicked. Howeve ...

Delete item from file

In the case that the variable author is defined, an update is made to the mongoDB document to add a new object { assignTo: author }. This will either create or update the existing document. If author is empty, I need to remove the assignTo field from the ...

a pair of browser windows displaying a web application built with ASP.NET MVC

We are currently in the process of developing an ASP.NET MVC web application for internal use within our organization. Our users' productivity can greatly benefit from having a larger screen space, which is why we have decided to provide each user wit ...

Slider with Dual Images: A Visual Comparison

I'm currently working on a webpage that features before and after images using a slider based on mouse movement to display both pictures. I am trying to incorporate multiple sliders on the same page but have been facing difficulties in getting them to ...

ClickAwayListener is preventing the onClick event from being fired within a component that is nested

I am encountering an issue with the clickAwayListener feature of material-ui. It seems to be disabling the onClick event in one of the buttons on a nested component. Upon removing the ClickAwayListener, everything functions as expected. However, with it e ...

Modify the UserAgent from IE 11 to IE 9 through programming adjustments

When I try to open a Report using Crystal Report Viewer in IE11, the design appears distorted. However, changing the user agent to IE9 resolves the design issue. How can I change the user agent string for my page without altering the entire web.config of ...

Index similar to JavaScript-Meadow

Is there a way to create a table of contents like the ones seen on sites such as JavaScript Gardens? How do they determine which section is currently active and are there any recommended JavaScript libraries that can help achieve this functionality? Edit: ...

Remove any actions that a view has linked to the app.vent

By invoking view.unbindAll(), will the events that I registered on the global event bus be removed? ...