Rearrange the parent object's structure based on the data and length of the child array

Is it possible to restructure parent data based on the child array data and its length? Should I stick with an array structure or consider changing the object array from the backend?

No IDs are present in the child arrays.

This is what has been accomplished:

this.arrays = [
  {
    id: '1',
    idbid: '0000000001618',
    name: 'ebi',
    rate: '400',
    bid: [
      {
        bid: 10000,
        date: '2022/12/12',
        value: 5000,
      },
      {
        bid: 10000,
        date: '2022/12/14',
        value: 8100,
      },
      {
        bid: 15000,
        date: '2022/12/15',
        value: 8100,
      },
    ],
  },
  {
    id: '2',
    idbid: '0000000001618',
    name: 'bio',
    rate: '100',
    bid: [
      {
        bid: 8000,
        date: '2022/12/13',
        value: 8000,
      },
    ],
  },
];

// Merge all item bids in the child array
let allVal: any = [];
allVal = allVal.concat(this.arrays.map((data) => data.bid).flat());
console.log(allVal);

// Get unique bids
var uniqueData = [];
allVal.forEach((item) => {
  let count = uniqueData.filter((x) => x.value == item.value).length;

  if (count == 0) {
    uniqueData.push(item);
  }
});
console.log(uniqueData);

// Find and merge into the parent array
const newArrays = uniqueData.map((obj) => {
  return this.arrays.find((data) =>
    data.bid.some((val) => val.value == obj.value)
  );
});
console.log(newArrays);

// Restructure custom arrays of parents
const remapArrays = newArrays.map((obj, index) => {
  return {
    id: index + 1,
    idbid: obj.idbid,
    name: obj.name,
    rate: obj.rate,
    bid: obj.bid[index]?.bid,
    date: obj.bid[index]?.date,
    value: obj.bid[index]?.value,
  };
});
console.log(remapArrays);

The result so far looks like this:

[
  {
    id: '1',
    idbid: '0000000001618',
    name: 'ebi',
    rate: '400',
    bid: 10000,
    date: '2022/12/12',
    value: 5000,
  },
  {
    id: '2',
    idbid: '0000000001618',
    name: 'bio',
    rate: '100',
    bid: 10000,
    date: '2022/12/13',
    value: 8100,
  },
  {
    id: '3',
    idbid: '0000000001618',
    name: 'ebi',
    rate: '400',
    bid: undefined,
    date: undefined,
    value: undefined,
  },
];

The expected output should be:

// Final expected output
this.customArrays = [
  {
    id: '1',
    idbid: '0000000001618',
    name: 'ebi',
    rate: '400',
    bid: 10000,
    date: '2022/12/12',
    value: 5000,
  },
  {
    id: '2',
    idbid: '0000000001618',
    name: 'bio',
    rate: '100',
    bid: 8000,
    date: '2022/12/13',
    value: 8000,
  },
  {
    id: '3',
    idbid: '0000000001618',
    name: 'ebi',
    rate: '400',
    bid: 15000,
    date: '2022/12/15',
    value: 8100,
  },
];

To test the code, visit Stackblitz

Answer №1

It is important to clarify certain aspects of the question:

  • Are we assuming that the value of "idbid" remains consistent across all elements in the original array?
  • Should the resulting array only contain the first date from each unique bid?

For the purpose of this explanation, I will assume a positive response to both questions.

  • Initially, when consolidating all child arrays:
allVal.concat(this.arrays.map((data) => data.bid).flat());

During this process, we are overlooking the uniqueness of values belonging to individual parent elements. For instance, the "rate" value differs between the first and second parent elements (i.e., "400" versus "100"). Hence, prior to flattening, it is necessary to map the bid arrays so that every child element encompasses data from its respective parent element:

// consolidate all item bids within child arrays
const allVal = this.arrays
  .map((dataWithBids) => {
    const { id, idbid, name, rate, bid: bidArr } = dataWithBids;
    // incorporate parent element data into each bid
    return bidArr.map((bidData) => ({
      idbid,
      name,
      rate,
      ...bidData,
    }));
  })
  .flat();

In the subsequent stage, the extraction of unique values can be accomplished as initially suggested or by leveraging the some method within an array:

// retrieve unique bids
const uniqueData = [];
allVal.forEach((item) => {
  const exists = uniqueData.some((x) => x.value == item.value);

  if (!exists) {
    uniqueData.push(item);
  }
});

At this juncture, with correct values secured, the next steps involve sorting them by date and assigning identifiers:

const sorted = uniqueData
  // organize by date
  .sort(
    (bidData1, bidData2) =>
      Date.parse(bidData1.date) - Date.parse(bidData2.date)
  )
  // assign ids
  .map((bidData, index) => ({
    ...bidData,
    id: index + 1 // or (index + 1).toString(),
  }));

The resultant array labeled sorted from the above operations aligns with the anticipated output.

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 allocate data to the stack

Below is the code showcasing my Stack Implementation class stack { private: int top; int elements[10]; public: Stack() { top = -1; for(int i=0; i < 10; i++) { e ...

Generate a multi-dimensional array using an array of specified keys

I'm having some trouble creating a nested array using an array of keys and assigning a value to the last nested item. For instance, if $value = 4; and $keys = ['a', 'b', 'c']; The desired output should be: [ 'a& ...

Cleaning up HTML strings in Angular may strip off attribute formatting

I've been experimenting and creating a function to dynamically generate form fields. Initially, the Angular sanitizer was removing <input> tags, so I discovered a way to work around this by bypassing the sanitation process for the HTML code stri ...

Get items from an array that have a property matching another array

Is there a more efficient way to create a new array with contact objects that have values matching those in selectedContact? selectedContact: number[] = [0,2] //value contacts: Contact[] = [{ firstName:"Dan"; lastName:"Chong"; email:"<a href="/c ...

Encountering an error stating "Promise not found" while running the 'npm start' command

Just starting out with Angular 2 and followed the 5 min Quickstart tutorial. I decided to give the ScotchIO example a try, using the exact code provided in the example. However, when running the npm start command after installing the node module through np ...

"Obtaining the file name rather than the file path using ngModel and ng2-file-upload: A simple guide

When a file is selected, I need to retrieve the file name and save it to the database. However, all I seem to be able to access is the fakepath of the file. //component.html <div class="col s12 file-field input-field" style="margin-left: -10px"> ...

Adjust the Express JS response to prevent certain specific values from being included

I am currently working on an Express application that is returning large decimal numbers as text in the responses. The issue arises when the numbers are either 'Infinity' or 'NaN'. I am looking for a way to replace these values with emp ...

Uncertainty surrounding the extent of a button's scope within an Angular application

(click) event in one instance of a component is causing the function in another instance to be triggered unexpectedly. I am having trouble describing this issue. For reference, I have included a working example on stackblitz. When clicking on both buttons ...

What is the appropriate array variable type to use with pointers in the C programming language?

When initializing a pointer to an int for an array, it is necessary to use the following notation: int data[] = {34,35,36}; int *ptr = &data[0]; This is because the variable data has a type of int[], which is why the declaration below results in warni ...

Working with Angular Forms and a Text Area

Utilizing angular forms within a dialog to gather strings has been quite successful. However, I have encountered an issue when attempting to bind the formController to a textarea. Despite my best efforts and scouring through documentation, I cannot seem to ...

Evaluating Angular/Typescript and its capabilities

I seem to be struggling with the concept of how eval functions in TypeScript/Angular. Can someone provide some guidance on how to make eval work in this scenario? Although the logic may not be perfect in this demo program, I just need help figuring out how ...

What are the benefits of incorporating component A into component B as a regular practice?

I am considering creating an instance of Component A within Component B, but I'm unsure if this is a best practice in Angular or if it will just cause confusion. Component A: This component generates a modal window asking the user to confirm file de ...

Are there any potential risks in sticking with Angular 2 instead of upgrading to a newer version?

Our current legacy app has been utilizing Angular 2.4 from the start. The package.json file contains numerous overrides for packages, leading us to use npm install --force during our build process due to peer dependency conflicts and unresolved dependencie ...

Not all elements are removed by an array

$channels = array('imaqtpies','imsoff','zzero71tv', 'kaptenen', 'onlySinged', 'nightblue3') ; $nr = 0; $callAPI = implode(",",$channels); $online = 'online.png'; $offline = ' ...

Having trouble getting the Angular2 [innerHtml] directive to render properly?

Is there a way to inject HTML code from one Angular component into another using Angular 2 tags? @Component({ selector: 'app-root', template: '<app-a [my-html]="my-html"> </app-a>', styleUrls: ['./app.component.c ...

PHP - Verify if a value exists within a nested array

I am working with a multidimensional array structured like this: $pover = Array ( [0] => Array ( [item_name] => "iPhone 5s Repair" [service_name] => "Touchscreen & LCD repair" ...

Creating an array within a mat table that is enclosed within an observable

I have a Parent List component that includes two child components: First Child List and Second Child List. In the Second Child List component, there is a Mat Table that receives input data for display. I create the data source in the ngOnChanges method usi ...

Tips for properly importing types from external dependencies in TypeScript

I am facing an issue with handling types in my project. The structure is such that I have packageA -> packageB-v1 -> packageC-v1, and I need to utilize a type declared in packageC-v1 within packageA. All the packages are custom-made TypeScript packa ...

What causes the appearance of the "?" symbol at the beginning of the URL and triggers a reboot of the app when moving through the absolute path?

I am facing an issue. In my multi-module application with lazy loading, I encountered a strange behavior when trying to navigate between child lazy modules. Transition from top module to bottom child module works fine, but routing from one bottom child la ...

The act of comparing within a for loop

As a newcomer to Java, I encountered an issue while working on a project that involves extracting data by comparing the results obtained from a for loop. The for loop is used to retrieve results from an SQL query, and the code for the for loop is as follow ...