Combining and Converting Arrays of Objects in JavaScript

I'm facing a problem with two arrays of objects structured like this...

const planned = [
    {
        '2023-01-06': 46,
        '2023-01-04': 45,
        '2023-01-05': 43,
        '2023-01-07': 53
    }
]
const actual =[
    {
        "2023-01-07": 12,
        "2023-01-06": 16,
        "2023-01-04": 14,
        "2023-01-08": 10,
        "2023-01-05": 12,
        "2023-01-03": 10
    }
]

I want to merge them into a single array of objects separating the date and its corresponding value. This is how I expect the final array to look:

const transformed =  [{
    date:"2023-01-03",
    actual:10,
    planned:0,
  },{
    date:"2023-01-05",
    actual:10,
    planned:5,
  },{
    date:"2023-01-06",
    actual:16,
    planned:46,
  },....

] I've tried coming up with a solution, but I'm struggling with the logic... Can anyone provide me with some guidance on how to tackle this? Is there a way to utilize the reduce prototype array or any other built-in methods for this task? Any assistance would be greatly appreciated.

Answer №1

One strategy to tackle this issue involves manipulating arrays and converting them into a flat map. This transformation allows for the creation of the desired output.

const planned = [
    {
        "2023-01-06": 46,
        "2023-01-04": 45,
        "2023-01-05": 43,
        "2023-01-07": 53,
    },
];
const actual = [
    {
        "2023-01-07": 12,
        "2023-01-06": 16,
        "2023-01-04": 14,
        "2023-01-08": 10,
        "2023-01-05": 12,
        "2023-01-03": 10,
    },
];

const convertToMap = (list) =>
    list.reduce((acc, curr) => ({ ...acc, ...curr }), {});

const actualStats = convertToMap(actual);
const plannedStats = convertToMap(planned);

const dates = [
    ...new Set([...Object.keys(actualStats), ...Object.keys(plannedStats)]),
];

const transformed = dates.map((date) => ({
    date,
    planned: plannedStats[date] || 0,
    actual: actualStats[date] || 0,
}));

console.log(transformed);

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

An issue encountered with res.download() following res.render() in Node.js

Just started working with Node JS and ran into an issue: Error: Can't set headers after they are sent. I've checked my code, and the problem seems to be related to res.download(); Is there a way to display the view without using res.render()? ...

Improper height of MathJax in the div element

I'm currently investigating why the MathJax render block is giving me an incorrect height for the div. Here's the code snippet: <div class="text-field" id='inner-text'>\(\sqrt{b^{a}\frac{\partial y}{& ...

Failed to fully install all dependencies for my project with yarn install

After cloning a project from gitlab, I attempted to install the dependencies using the yarn install command. However, there are several dependencies that yarn is unable to install and it keeps showing the error message: info There appears to be trouble wit ...

Error: Attempting to access the 'style' property of a non-existent element

function showNotes() { var ThemeValues = "<%=str3%>" if (ThemeValues.value == "MyCity-Social") { document.getElementById("TextBox1").style.visibility = "visible"; document.getElementById("TextBox2").style.visibility = "v ...

Set the height of the document body to be "100%" using the style property

I'm trying to figure out the html tag in order to change the background image, but I keep getting an error that says: "TypeError: document.html is undefined." Here's the code I've been using: function init(){ document.html.style.ba ...

In Angular JS pagination, the previous filter value is stored in $LocalStorage for future reference

One view displays all order records in a tabular format with 10 records per page. A filter is set to show only paid orders, which pops up filtered data when selected. An issue arises when closing the pop-up window and navigating to the next page of the t ...

FancyBox: Struggling to adjust dimensions accurately

Currently using Fancybox 1.2.6 in conjunction with JQuery 1.2.6, Sample Code: <script type="text/javascript> $(document).ready(function() { $("a.iframe").fancybox({ 'width' : 300, 'hei ...

JavaScript Code: Empty a text box when a different one is active

Looking for a solution to clear the content of one textbox when the user interacts with another in HTML and JavaScript. <input id="tb1" type="text" name="textbox1"> <input id="tb2" type="text" name="textbox2"> Seeking JavaScript code that wil ...

What's preventing the bind click event from working properly?

I have a unique Vue application setup like this: index.html structure: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>vuejs-test01</title> <link href="./src/assets/styles/style. ...

Manipulate the contents of an HTML class using Javascript to substitute text with an empty string

Is there a way to create a JavaScript function that can remove text upon clicking from multiple HTML fields with the same class? I am facing an issue where my function is not clearing the data in the target field when "Yes" is selected in the trigger. Re ...

Using a Svelte click event to toggle a boolean value in an array from a div

How can I modify the toggle functionality to work on any click event, not just on a button, in order to trigger a state change regardless of the element clicked? ToolBar.ts export default class ToolBar { options:Array<ToolBarOptions>; const ...

Getting access to scope variables in an Angular controller written in ES6 style can be achieved by using

In my new Angular project, I decided to switch to using ES6 (Babel). However, I encountered an issue where ES6 classes cannot have variables. This led me to wonder how I could set my $scope variable now. Let's consider a simple controller: class Mai ...

Effective sparse translation between whole numbers

I am in the process of developing a specialized regular expression engine that utilizes finite automata. My goal is to manage numerous states, each equipped with its own transition table mapping unicode code points (or UTF-16 code units; I have yet to fina ...

Encountering a compilation error when implementing ActionReducerMap in combination with StoreModule.forFeature

In my Angular project, the structure is organized as follows: /(root or repo folder) |_ projects |_ mylib (main library to be exported from the repo) |_ sample-app (created for testing 'mylib' project in other projects) To manage appli ...

Is there a way to ensure my Vue variable is declared once the page has fully loaded?

I have implemented a v-for loop in my code: <div v-for="(user, index) in users" :key="index" :presence="user.presence" class="person"> <span class="cardName h4">{{ user.name }}</span> ...

I found myself unable to navigate the web page through scrolling

Experiencing difficulty scrolling on my web page with the code provided. If you'd like to see the issue in action, you can view a live demo HERE JavaScript <script> $(window).bind('scroll', function () { if ($(window).scrollTop ...

What is the method for transforming latitude and longitude coordinates into a physical address for a website?

I'm working with an API that provides latitude and longitude coordinates, and I need to retrieve the address information (city, area, etc.) based on these values. For example, there is a website like where if we enter the IP address of a location, i ...

What is the process of extracting a value from an array of objects based on another parameter?

Given the array below which contains objects with nested arrays, my goal is to retrieve the value 'AUS Eastern Standard Time' when 'Australia/Melbourne' is passed to the array. Although I attempted to use the code var winTimeZone = arr ...

The HTML code for the base64 image conversion failed to load

I am facing an issue with handling HTML strings containing base64 image tags generated by Summernote. I have a process in place where I load the image elements, convert them to image blobs, upload them to get the image-url, and then update the src attribut ...

Mongoose doesn't support saving extensive text-data

I am facing a challenge while trying to save an extensive text into my mongodb database as it keeps crashing. I am in the process of creating a snippet manager and below you can find the error code I encountered: { [MongoError: Btree::insert: key too larg ...