Create a fresh array by merging two existing arrays together

My project involves working with two separate arrays. The first array contains normal date values:

    var = [
    "2022-05-01",
    "2022-05-02",
    ...
    "2022-05-30"
]

The second array consists of objects that contain specific information:

    var b = [
  {
    "k_id": "6dcb67eb-1c8a-4239-9446-f9d8f6a68086",
    "v_id": "aacc1765-a1d3-43c3-8233-beae19d258e5",
    ...
  },
  {
    "k_id": "6dcb67eb-1c8a-4239-9446-f9d8f6a68086",
    ...
  }
]

I need to transform the new array into a specific format, which should include data related to each date present in the objects. If a date from the object matches a date in the main array, an object should be created with properties based on that info. Otherwise, a blank object should be generated for that date.

Unfortunately, the current output is not as expected:

It only displays the first entry correctly while the rest appear as blank entries. Here's the code snippet I'm using:

var a = {};
          dateArr = [];
          for (var j = 0; j < this.date_val.length; j++) {
            debugger;
              var b = {}
              console.log(val2.value[j]);
              
              if (val2.value.length > 0) {
                const newKey = this.date_val[j];
                b[newKey] = val1.data;
                a = {
                    value:
                      val2.value[j] != undefined ? val2.value[j].value : "",
                    value_id:
                      val2.value[j] != undefined
                        ? val2.value[j].v_id
                        : undefined,
                    date:
                      val2.value[j] != undefined
                        ? moment(val2.value[j].start_date).format(
                            "YYYY-MM-DD"
                          )
                        : this.date_val[j],
                  };
              } else {
                a = {
                  value: "",
                  value_id: undefined,
                  date: this.date_val[j],
                };
              }
            dateArr.push(a);
          }
          this.nameArray.push({
            key: val1.key,
            key_val: val1.id,
            date: dateArr,
          });

If anyone can provide assistance or guidance on how to address this issue, it would be greatly appreciated. Thank you!

Answer №1

var a = [
  "2022-05-01",
  "2022-05-02",
  "2022-05-03",
  "2022-05-04",
  "2022-05-05",
  "2022-05-06",
  "2022-05-07",
  "2022-05-08",
  "2022-05-09",
  "2022-05-10",
  "2022-05-11",
  "2022-05-12",
  "2022-05-13",
  "2022-05-14",
  "2022-05-15",
  "2022-05-16",
  "2022-05-17",
  "2022-05-18",
  "2022-05-19",
  "2022-05-20",
  "2022-05-21",
  "2022-05-22",
  "2022-05-23",
  "2022-05-24",
  "2022-05-25",
  "2022-05-26",
  "2022-05-27",
  "2022-05-28",
  "2022-05-29",
  "2022-05-30",
];

var b = [
  {
    k_id: "6dcb67eb-1c8a-4239-9446-f9d8f6a68086",
    v_id: "aacc1765-a1d3-43c3-8233-beae19d258e5",
    key: "Testing",
    value: "999",
    start_date: "2022-05-06T00:00:00.000Z",
    end_date: "2022-05-06T00:00:00.000Z",
  },
  {
    k_id: "6dcb67eb-1c8a-4239-9446-f9d8f6a68086",
    v_id: "ad95cc4a-ec72-4d6e-a452-f519358f265d",
    key: "Testing",
    value: "189",
    start_date: "2022-05-08T00:00:00.000Z",
    end_date: "2022-05-08T00:00:00.000Z",
  },
];

let results = a.map((dateString, idx) => {
  // Need to handle time parsing and comparison
  let bWithMatchedIndices = b.find(
    ({ start_date }) => dateString === start_date.split("T")[0]
  );

  if (bWithMatchedIndices?.start_date.split("T")[0] === dateString) {
    return {
      date: dateString,
      value: bWithMatchedIndices.value,
      value_id: bWithMatchedIndices.v_id,
    };
  } else {
    return {
      date: dateString,
      value: "",
      value_id: "",
    };
  }
});
console.log(results);

Answer №2

To find a match between dates in array A and B, simply iterate over the dates in A and search for a corresponding date in B. Then, create an object containing the necessary attributes and add it to the final array.

interface NewItem {
    date: string,
    value: string,
    value_id: string
}

function transform(a: any[], b: any[]): NewItem[] {
    let newArray: NewItem[] = []

    a.forEach(item => {
        const objectFound = b.find(x => x.start_date.split('T')[0] === item)

        if (objectFound) {
            newArray.push({ date: item, value: objectFound.value, value_id: objectFound.v_id })
        } else {
            newArray.push({ date: item, value: '', value_id: '' })
        }
    })

    return newArray
}


console.log(transform(a, b))

If needed, you can also define interfaces for the original objects in arrays A and B. However, following this approach should guide you in the right direction.

Check out the output at this Playground.

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 jQuery in Wordpress to Toggle Content Visibility

Currently, my website pulls the 12 most recent posts from a specific category and displays them as links with the post thumbnail image as the link image. To see an example in action, visit What I am aiming to achieve is to enhance the functionality of my ...

Unable to submit data to PHP script using Angular 2

I am currently attempting to send a post request to a PHP script that contains the necessary data I require. Within home.component.ts: import { Component, OnInit } from '@angular/core'; import { UserComment } from '../definition/us ...

The EXIF-JS data is becoming inaccessible beyond the method's scope

Currently, I am in the process of developing a web application using Angular 8. My main objective is to access the exif data of an input image outside the getData method by assigning the obtained data to a global variable. However, when attempting to acces ...

Associating a mouse click with elements within a repetitious function

Currently, I am importing children of element with ID #parentEle, creating a duplicate of each child and adding it to an array with a new ID - #eleCopy(i). I am facing an issue where I am trying to implement a click function on the original imported objec ...

Typescript: Implementing the 'types' property in a function returned from React.forwardRef

I'm exploring the option of adding extra properties to the return type of React's forwardRef function. Specifically, I want to include the types property. Although my current implementation is functional, given my limited experience with TypeScri ...

Every time I try to access Heroku, I encounter an issue with Strapi and the H10 error code

Upon opening Heroku and running the command "heroku logs --tail", my app encountered a crash and I can't seem to locate my Strapi application in Heroku. 2020-05-04T19:05:38.602418+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GE ...

The form submission is yielding an incorrect value

When creating multiple form groups, the issue arises where submitting one form returns the value of the last entered form. export class ExpansionOverviewExample { panelOpenState = false; tables: string[] = ['one', 'two', 'three ...

Requesting AJAX page yields a null $_GET parameter

Content loaded dynamically via AJAX methods. The base page is index.php, and profile.php is the page that gets loaded. The jQuery code snippet below has nothing to do with an HTML request: $('<a/>', {href: '?userID='+post[' ...

Performance issues arise in Angular when multiple DOM elements are added through dynamic components with binding, causing lagging

I have implemented a nested expand/collapse feature using dynamic components in Angular 5. Although the functionality works well, the browser crashes or the scroll stops working when loading multiple DOM elements (resulting in jerky scroll). This feature ...

What steps should I follow to ensure that TypeScript is aware of the specific proptypes I am implementing?

Is there a way to instruct TypeScript on the prop types that a component is receiving? For example, if multiple is set to true, I would like TypeScript to expect that selectValue will be an array of strings. If it's not present, then TypeScript should ...

Angular application utilizes role-based approach for populating elements

I am currently developing a project that involves tightly coupling UI components with the permissions assigned to the logged-in user role. (Angular 4 for front end and Spring for backend) Upon successful login, the backend server returns a user object alo ...

What is the easiest way to simulate the Ctrl+C key event using jQuery?

I need to programmatically simulate pressing Ctrl+C in order to copy text from a page. My initial attempt looked like this: $('#codetext').click( function() { $("#codetext").trigger({ type: 'keydown', which: 99 }); } Her ...

What is the best way to fetch information from an API using Angular5 with Material2 components?

Here are the 'table.component.html' and 'table.component.ts' files where I am pulling data from an API to display in a table. Below is the object received from the API: [ {position: 1, name: 'Hydrogen', weight: 1.0079, sym ...

Display a loading indicator in Angular during app initialization with APP_INITIALIZER

Is there a way to display a waiting indicator while the Angular app is running the app_initializer code? Currently, I can display a waiting indicator until the app is fully loaded. However, once the page loads, it remains empty until the app_initializer c ...

arrange elements by their relationship with parents and children using typescript and angular

Here is a list that needs to be sorted by parent and child relationships: 0: {id: 7, name: "333", code: "333", type: 3, hasParent: true, parentId: 4} 1: {id: 6, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: false, parentId: null} 2: {id: 5, name: ...

Images showing Strava heat maps retrieved through API

Check out this amazing heatmap created by Strava! I'm curious about how they were able to achieve this - it seems like they are using the API to request overlay images based on the network tab. I have my own geo data, but I'm wondering how I can ...

Getting rid of redundant elements in an array using Javascript or AngularJS

Case Study 1 A situation arises where an API I am using returns an array with duplicate values. var originalArray = [{id:1, value:23},{id:1, value:24},{id:1, value:22},{id:2, value:26},{id:3, value:26}]; //example Inquiry 1 -> How can I remove the du ...

AngularJS wildcards can be used in filters for a versatile approach

Is there a more efficient way to filter a list of values using wildcards? searchString = "ab*cd" The goal is to retrieve all values that begin with "ab" and end with "cd". One approach I've tried involves splitting the string into multiple substrin ...

Issue in JavaScript / D3.js: When button is clicked, data fails to update and instead new positions are plotted

When the user clicks a button, both the red woman (unvaccinated) and the blue woman (vaccinated) should be updated to reflect the new value. At present, when the button is clicked, the red woman updates correctly but the blue woman is recreated in the loca ...

Exploring Realtime Database Querying with Firebase 5.0

I'm struggling to retrieve all the data from my RTD and store it in an array for iteration. The code below is returning 'undefined'. What could be the issue? export class AppComponent { cuisines$: Observable<any[]>; cuisines: any[ ...