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

Unable to modify headers after they have already been sent to the client - an error has occurred

I am encountering an issue when trying to redirect the page to another page. Everything works fine with the first post request, but starting from the second one, I keep getting this error message: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after t ...

Tips for formatting strings to be compatible with JSON.parse

I'm encountering an issue with my node.js application where I am attempting to parse a string using JSON.parse. Here is the code snippet: try{ skills = JSON.parse(user.skills); }catch(e){ console.log(e); } The string stored in user.skill ...

The child's status is not displaying correctly

I am in the process of developing a blackjack app and facing an issue with re-rendering hands after the initial deal. I have tried updating the state in App.js and passing it to PlayerHand.js for rendering, but the child component does not refresh despite ...

What are the steps to retrieve information from your personal server using Astro?

I have successfully set up a NodeJS server using Express and Astro for the frontend, with SSR configured through the Astro adapter for NodeJS. My current challenge is fetching data from the backend, and I am unsure of the correct approach to do so. Below ...

Retrieve the value of an input text within a table data cell using JavaScript

I have set up a table using CGridView, which includes input text fields for user input. The problem I'm facing is that I can retrieve the text from table cells without input fields, but not from those containing input fields. PHP: <?php $this-> ...

NodeJs: Dealing with package vulnerabilities stemming from dependent npm packages - Tips for resolving the issue

Is there a way to address npm vulnerabilities that are dependent on another package? For instance, I'm encountering an error where the undici package relies on the prismix package. Things I have attempted: Executed npm audit fix Ensured Prismix is u ...

Generate listview items containing anchor tags automatically

I am currently developing a web application using Jquery Mobile. After retrieving data from a webservice function, I am utilizing an ajax call to display this data on my webpage. $('[data-role=page]').on('pageshow', function () { var u ...

What is the process for updating the class of the target button?

I am new to using Vue and struggling to achieve a specific functionality. I have multiple buttons and I want to ensure that only one button can be selected at a time. Currently, I have tried implementing it with the following code: :class="isActive ? ...

The verification of form is not done using an if statement

There are two forms in my code named formA and comments that I need to submit via AJAX. However, the current if and else conditions do not correctly identify the form and always trigger the alert message hello3. Here is the JavaScript function: function ...

The function estimatedDocumentCount() actually returns an object rather than a numerical value

I am currently working on a feature in my web application where I want to display the number of documents stored in my MongoDB database whenever a user visits the homepage. To achieve this, I have outlined the implementation process in the following diagra ...

Ways to speed up the initial loading time in Angular 7 while utilizing custom font files

Storing the local font file in the assets/fonts folder, I have utilized 3 different types of fonts (lato, raleway, glyphicons-regular). https://i.stack.imgur.com/1jsJq.png Within my index.html under the "head" tag, I have included the following: <lin ...

Encountering an issue while retrieving data from my personal server: "Error message states 'Unexpected end of JSON input'."

As a beginner in Backend development, I decided to experiment with API calls and Client-Server interactions. const express = require("express"); const cors = require("cors"); const fetch = require("node-fetch"); const app = e ...

Vue.js fails to update view after file status changes

I am currently working with Vue.js and have the following code snippet: <div class="file has-name is-fullwidth is-light"> <label class="file-label"> <input class="file-input" ...

The functionality of the jQuery script is not operating optimally, causing the expected alert to not be displayed

I implemented this jQuery script: $('input[name="add-post"]').on('click', function(form) { form.preventDefault(); for ( instance in CKEDITOR.instances ) CKEDITOR.instances[instance].updateElement(); $.ajax({ typ ...

The error message "File is not defined" in the context of express is throwing

I am attempting to convert a base64 string into an image file and send it to Firebase through Express. Everything is functioning correctly on the frontend, except for this particular section: const convertBase64ToFile = (base64String, fileName) => { ...

Is it possible for a property to be null or undefined on class instances?

Consider this TypeScript interface: export interface Person { phone?: number; name?: string; } Does having the question mark next to properties in the interface mean that the name property in instances of classes implementing the interface ca ...

Is jQuery Autocomplete functioning properly on outdated browsers, but not on newer ones?

Here is the JSON data I have for my auto complete feature { "list" : [ { "genericIndicatorId" : 100, "isActive" : false, "maxValue" : null, "minValue" : null, "modificationDate" : 1283904000000, "monotone" : 1, "name":"Abbau", ...

Typescript check for type with Jest

Assume there is an interface defined as follows: export interface CMSData { id: number; url: string; htmlTag: string; importJSComponent: string; componentData: ComponentAttribute[]; } There is a method that returns an array of this obj ...

Set up a timed event for a .js file to execute

I am currently exploring options for automatically running a JavaScript file multiple times per day, similar to Task Scheduler on Windows. Right now, I manually run the file in VS Code or Command Prompt using the command "node file.js". Is there a way to a ...

Set $scope.model childs to an empty string or a null value

While working on a form, I am using a $http request to send the information through Angular in the following manner: $http({ method:"POST", url: "controllers/servicerequest.php", data: { servicerequest: $scope. ...