Leveraging ForEach to merge two arrays and generate a fresh entity

I am in search of my final result which should be as follows:

result = [{x: '12/12', y: 90 }, {x: '12/11', y: 0}, {x: '12/10', y: 92}, {x: '12/9', y: 0}, ... ]

Currently, I have two arrays to work with. The first array represents the last 30 days and was generated using momentjs in this manner:

const lastThirtyDays = [...new Array(31)].map((i, idx) =>
    moment()
      .startOf('day')
      .subtract(idx, 'days')
      .format('MM/D'),
  );

This produces the following array of dates:

["12/12", "12/11", "12/10", "12/9", "12/8", "12/7", "12/6", "12/5", "12/4", "12/3", "12/2", "12/1", "11/30", "11/29", "11/28", "11/27", "11/26", "11/25", "11/24", "11/23", "11/22", "11/21", "11/20", "11/19", "11/18", "11/17", "11/16", "11/15", "11/14", "11/13", "11/12"]

The second array consists of a collection of numbers associated with certain dates, depicted as follows:

const sampleSet = [
  { date: '2019-12-11', number: 100 },
  { date: '2019-12-10', number: 99 },
  { date: '2019-12-08', number: 101 },
  { date: '2019-12-07', number: 90 },
  { date: '2019-12-05', number: 98 },
  { date: '2019-12-01', number: 96 },
  { date: '2019-11-28', number: 99 },
];


In an attempt to merge these arrays into an x-y dataset, I initially utilized a forEach loop as shown below:

const createDateSet = () => {
  let set = [];
  lastThirtyDays.forEach((date, i) => {
    if (
      sampleSet[i] &&
      sampleSet[i].date &&
      moment(sampleSet[i].date).format('MM/D') === date
    ) {
      set.push({ x: date, y: sampleSet[i].number });
    } else {
      set.push({ x: date, y: 0 });
    }
  });
};


However, this approach did not yield the desired outcome. Only one matching entry was found. Subsequently, I attempted to iterate over both arrays simultaneously, resulting in the implementation illustrated below:

const createDataSetBothArrays = () => {
  let set = [];
  lastThirtyDays.forEach((date, i) => {
    let dateItem = sampleSet[i];
    if (dateItem) {
      sampleSet.forEach((datum, i) => {
        if (moment(datum.date).format('MM/D') === date) {
          set.push({ x: date, y: datum.number });
        }
      });
    } else {
      set.push({ x: date, y: 0 });
    }
  });
};


Despite this revised strategy, there remained inconsistencies between the paired numbers.

What would constitute the correct course of action for resolving this issue?

Thank you!

Answer №1

To retrieve the desired dateSet.number, follow these steps with a map and find method:

lastThirtyDays.map(monthAndDay => {
 const date = moment('12/11/2019').format('MM-DD-YYYY');
 const set = sampleSet.find(set => set.date === date);

 return { x: monthAndDay, y: set ? set.number : 0 };
});

Answer №2

To ensure better compatibility and accuracy in your data comparison, consider aligning the date format in your lastThirtyDays array with that of your sampleSet. This step not only facilitates a precise cross-reference but also offers enhanced safety when dealing with dates spanning multiple years. You can always revert to your preferred display style during result construction.

In cases where a matching date is not located, you can assign a default value of 0 to number using || {number: 0}.

const sampleSet = [ { date: '2019-12-11', number: 100 }, { date: '2019-12-10', number: 99 }, { date: '2019-12-08', number: 101 }, { date: '2019-12-07', number: 90 }, { date: '2019-12-05', number: 98 }, { date: '2019-12-01', number: 96 }, { date: '2019-11-28', number: 99 }, ];
const lastThirtyDays = [...new Array(31)].map((i, idx) => moment().startOf('day').subtract(idx, 'days').format('YYYY-MM-DD'));

const result = lastThirtyDays.map(day => ({
  x: moment(day).format('MM/D'), 
  y: (sampleSet.find(({date}) => date === day) || {number: 0}).number 
}));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

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

Utilizing a font URL imported through a script

I am currently working on incorporating the pdfmake package into my application. In order to load fonts, a list of URLs is required during initialization. However, the fonts I am using are managed by npm and Vite, so they do not have fixed URLs. Here' ...

Transforming the NavBar in React: A guide to dynamically updating values

I am facing an issue with my NavBar that changes based on certain events. The current setup works fine, but I don't want to render it in every class that loads a new page. Initially, I had the NavBar rendering inside App.js so it could appear on all p ...

Guide to utilizing element reference with material UI components in Angular

I am facing difficulty in accessing the reference of an element. My intention is to wrap the material UI elements within a div and set the opacity: 0 so that it remains hidden in the HTML, allowing me to handle the value in my component.ts file. The main g ...

Assign a class to a DIV element depending on the ID of an object using Angular

I'm trying to dynamically add a class to a div based on the id of a field in an object. However, my code doesn't seem to be working as expected. Can someone help me debug this? <ng-container *ngFor="let item of cards"> <d ...

Encountering a segmentation fault while attempting to retrieve a character from a string within a multidimensional array

I'm attempting to extract a specific character from a string within a 2D array. The current code I have looks like this: Board setData(Board b, char c, int i, int j) { printf("setData called\n char = %c, i = %d, j = %d\n", c, i, j); int ...

Creating a single Vuetify expansion panel: A step-by-step guide

Is there a way to modify the Vuetify expansion panel so that only one panel can be open at a time? Currently, all panels can be closed which is causing issues. I would like the last opened panel to remain open. I also want to prevent closing the currently ...

Display PHP Array data in a table on a webpage

I need help arranging the results from a MYSQL database into an HTML table. Right now, each item is displayed in one column per row. Here is my current code: <?php $catagory=$_GET["q"]; $con = mysql_connect("localhost","cl49-XXX","XXX"); if (!$con) ...

"Sending a file (Image) through NextJS API Routes to an external API: A step-by-step guide

I am currently using a combination of NextJS (SSR and SPA for authorized dashboard) with Django Rest FW on the backend. To handle authentication, I employ JWT tokens stored in cookies. As a result, it is necessary to have a middleware at /pages/api/* that ...

Tips for effectively utilizing MeteorPad: (Note: ensure to use at home instead of at work due to potential firewall or proxy issues)

UPDATE: It's possible that the issue is related to a firewall or proxy. MeteorPad doesn't work at my workplace, but it works fine at home. I've been attempting to use MeteorPad () but I'm encountering some difficulties. The bottom are ...

How can the distinctions between two bars be illustrated in high charts?

Is there a way to display different values on a new line between two bar charts using Highcharts plugins? I have created a simple bar chart in Highcharts, but I am looking to show the difference between the two bars on a new line. The concept is illustrate ...

JavaScript threw an error because it encountered an unexpected or invalid token

I can't seem to identify the error in this code. Can someone please help me correct it? document.write(' <div> <a href=http://www.socialsignal.ir style=\'\\padding:5px;text-decoration: none;border: 1px solid #555;ba ...

Guide to altering the color of a list item when hovering in HTML

Is there a way to change the color of the <li> element only when hovering over it, without affecting its parent or child elements? Here is an example: HTML: <div id="tree"> <ul> <li>apple</li> <li>banana</l ...

Is the performance impacted by using try / catch instead of the `.catch` observable operator when handling XHR requests?

Recently, I encountered an interesting scenario. While evaluating a new project and reviewing the codebase, I noticed that all HTTP requests within the service files were enclosed in a JavaScript try / catch block instead of utilizing the .catch observable ...

Tips for modifiying date format in React app

I'm encountering an issue where I can't modify the date format, preventing me from displaying the date on the frontend. Currently, I'm utilizing the dateformat package. import dateFormat from "dateformat"; const EditFinancialInfo ...

Angular 2 Update RC5: Router Provider Not Found

I'm encountering an issue with the latest Angular 2 RC5 router (router version is RC1). Below is the error log from the dev console: EXCEPTION: Error in /templates/app.component.html:2:0 ORIGINAL EXCEPTION: No provider for Router! This is how my ap ...

Tailwind does not display font sizes using random values

I am attempting to adjust the size of a span element based on a number from a variable: export default async function Tags() { const tags = await getTags(); return ( <div> <Suspense> <div className="flex flex-wrap ...

Incorporating transitions within a styled component using @emotion/core

I'm currently working on adding a smooth transition effect when a button is clicked. The code that adjusts the isOpen property is functioning correctly. However, I'm facing an issue where instead of animating, the content just flips abruptly. I a ...

Steps for resolving "TypeError: Unable to read properties of undefined (reading 'useSystemColorMode')"Ready to overcome this particular error message?

While working on a project with ChakraUI and React JS, I encountered an error at the start that read, "TypeError: Cannot read properties of undefined (reading 'useSystemColorMode')". I have not made any changes to the global theme in Chakra, j ...

Tips for testing views in ember.js using unit tests

We are currently delving into the world of Ember.js. Our development process is completely test-driven, and we aim to apply the same methodology to Ember.js. Having prior experience in test-driven development with Backbone.js apps using Jasmine or Mocha/Ch ...

Comparing v-show(true/false) and replaceWith: Exploring the best practice between Vue and jQuery

Currently, I am in the process of learning vue.js and have a question regarding the best approach to implement the following scenario: https://i.sstatic.net/2YBEF.png https://i.sstatic.net/YCEHG.png The main query is whether it is acceptable in HTML to w ...