arranges the objects in the array based on the attribute of the child objects within the array

Apologies for my limited English proficiency, I hope everyone can follow along. I am dealing with an array:

const arr=[  
  {
    name:"c",
    pay:[{
      name:"c",
      date: "2020-10-02"
    },{
      name:"cc1",
      date: "2020-10-03"
    },{
      name:"cc2",
      date: "2020-09-28"
    }]
  },{
    name:"a",
    pay:[{
      name:"aa",
      date: "2020-10-05"
    },{
      name:"aa1",
      date: "2020-10-03"
    },{
      name:"aa2",
      date: "2020-10-04"
    }]
  }, {
    name:"b",
    pay:[{
      name:"bb",
      date: "2020-10-10"
    },{
      name:"bb1",
      date: "2020-10-04"
    },{
      name:"bb2",
      date: "2020-10-01"
    }]
  }
];
Const date= new Date("2020-10-05");

I am looking to arrange the parent elements based on the date field, with the one closest to the date variable coming first. The desired result is:

const arr=[
        {
    name:"a",
    pay:[{
      name:"aa",
      date: "2020-10-05"
    },{
      name:"aa1",
      date: "2020-10-03"
    },{
      name:"aa2",
      date: "2020-10-04"
    }]
  },{
    name:"b",
    pay:[{
      name:"bb",
      date: "2020-10-10"
    },{
      name:"bb1",
      date: "2020-10-04"
    },{
      name:"bb2",
      date: "2020-10-01"
    }]
  }, 
  {
    name:"c",
    pay:[{
      name:"c",
      date: "2020-10-02"
    },{
      name:"cc1",
      date: "2020-10-03"
    },{
      name:"cc2",
      date: "2020-09-28"
    }]
  }
]

My approach involves calculating the absolute difference Math.abs(date - date in array) to determine the order of parent elements. However, I am struggling with handling the logic of each sub-array. Any assistance would be greatly appreciated. Thank you.

Answer №1

To tackle the nearest date logic, I suggest creating a custom function like absDate, which can be utilized with Array.sort.

For example:

const arr=[{name:"c",pay:[{name:"c",date:"2020-10-02"},{name:"cc1",date:"2020-10-03"},{name:"cc2",date:"2020-09-28"}]},{name:"a",pay:[{name:"aa",date:"2020-10-05"},{name:"aa1",date:"2020-10-03"},{name:"aa2",date:"2020-10-04"}]},{name:"b",pay:[{name:"bb",date:"2020-10-10"},{name:"bb1",date:"2020-10-04"},{name:"bb2",date:"2020-10-01"}]}];

const targetDate = new Date("2020-10-05");

const absDate = (record, targetDate) => Math.min(...
    record.pay.map(entry => Math.abs(new Date(entry.date) - targetDate)));

arr.sort((x, y) => absDate(x, targetDate) - absDate(y, targetDate));  
  
console.log(arr);
  

Answer №2

To organize the sub array based on their date, you can utilize the sorting function and retrieve their first entry to facilitate sorting of the parent object.

const arr = [{name:"c",pay:[{name:"c",date:"2020-10-02"},{name:"cc1",date:"2020-10-03"},{name:"cc2",date:"2020-09-28"}]},{name:"a",pay:[{name:"aa",date:"2020-10-05"},{name:"aa1",date:"2020-10-03"},{name:"aa2",date:"2020-10-04"}]},{name:"b",pay:[{name:"bb",date:"2020-10-10"},{name:"bb1",date:"2020-10-04"},{name:"bb2",date:"2020-10-01"}]}];

const date = new Date("2020-10-05");

const getClosestDate = (dates, target) => {
  return dates.map(({date}) => Math.abs(new Date(date) - target)).sort((a, b) => a - b).shift();
}

const sortByDate = (arr, date) => {
  return arr.sort((a, b) => getClosestDate(a.pay, date) - getClosestDate(b.pay, date));
}

const sorted = sortByDate(arr, date);

console.log(sorted);
.as-console-wrapper { max-height: 100% !important; }

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

Is there a way to insert copied links onto separate lines?

I have a list of links to Google search results. I have a checker that allows me to mark the links and copy them. My code is functioning properly, but I want each link to appear on a new line. ... Can someone please help me? I've attempted to add "< ...

Bug causing connection issues in Node.js when dealing with IP redirection

I recently encountered an issue with NodeJS while using a kafka node on a node-red instance installed on my RPI3. Let me paint you the scenario: I have a cluster set up with a functioning Kafka instance. The machine hosting the Kafka broker has a private ...

Transfer user data from users.js to app.js

I have developed a multiplayer game with a login system in place. To manage user data, I store information in users.js and need to pass this data to my app.js. Here is my app.js // Code for app.js goes here And here is my users.js // Code for users.js ...

Step-by-step guide to sending RESTful requests using Angular's $http service

Currently, I am working with Nodejs and my route has this structure: router.get("/profil/:id",function (req,res) { }); I am looking to push data from my angular controller using the $http service. ...

Vue struggles to handle data coming from a composable function

For my specific case, I need to verify whether the user has subscribed to my product through both Stripe and Firebase. To accomplish this, I created a composable function that checks for the current subscription in the Firebase collection. If the user cur ...

Retrieving the date input from a React form powered by Bootstrap

Is there a way to extract a specific timestamp in the format yyyy-mm-dd from the code snippet below? handleDateChange = e => {} <Form.Group as = {Col}> <Form.Control type = "date" value = { this.state.closingDate } onChange = { ...

swap out the CSS class for my own class dynamically

When I display HTML code like this <div class="btn btn-pagination"> <i class="fa fa-angle-right"></i> </div> and want to replace fa fa-angle-right with myClass when the page loads. I attempted: $(document).ready(function () { ...

Troubleshooting Type Conversion Error in ASP.NET MVC Controller

I have been working on an application that utilizes the following HTML and JavaScript. The user is required to input 5 props and then click on the 'Create' button. Subsequently, the JavaScript code compiles all of these props into a list before s ...

Can JQuery be used to identify the CSS styles applied to selected elements?

Highlight the text by selecting it and clicking a button. If the text is already highlighted, clicking the button should make the selected text return to normal. Can this be achieved using jQuery and a single button? Is it possible to identify the CSS st ...

Trouble arises when attempting to establish an isolated scope within Angular alongside UI Bootstrap

My table of data is set up with AngularJS, and one of the columns is calculated using a function in the controller. On my webpage, I have a button that opens a modal. When I use UI Bootstrap to open the modal, it creates a new isolated scope (child of the ...

Can we programmatically switch to a different mat-tab that is currently active?

Looking to programmatically change the selected mat-tab in a TypeScript file. I came across a solution for md-tab, but I need it for mat-tab. I attempted the suggested solution without success. Here's what I tried: HTML <button class="btn btn- ...

The value assigned to a dynamically created array in a void function may not be the same when returned in the main() function

Having a bit of trouble with dynamic arrays in my C program. Everything was running smoothly until I was required to move the creation of the dynamic array into a separate void function. After doing so, the program continued to work fine until I needed to ...

Utilizing Jquery to interchange two values and update styling

I am looking to create a script that allows me to select a black div by clicking on it (turning it red), and then transfer the value from the black div into a white div with another click. The functionality works as expected when swapping values between tw ...

Uh-oh! You can't perform image transformations without SciPy installed. Make sure to install

Currently, I am utilizing transfer learning to perform feature extraction on medical images using the imagedatagenerator. The version of pillow I am working with is 2.8.0, and the images are single-channeled in jpeg format. In my IDE, it shows that SciPy v ...

Ways to prevent false activation of functions due to changes and clicks

I have a text box and a clear button. When the user inputs something in the text box and then clicks out of it, a function called 'validate()' is triggered to perform an action. However, when I click the clear button instead and trigger another f ...

Assigning a value to a char variable from a constant char pointer

Check out this C code snippet I have: int main (int argc, const char *argv[]){ int counter = 1; char input[1000000]; while(argv[counter] != NULL){ input[counter] = argv[counter] } return 0; } An error is thrown stating "incompatible pointer to integer ...

What is the best way to trigger the download of an image file created by PHP to a user's computer?

My PHP code (upload.php) allows users to upload an image from index.html, resize it, add a watermark, and display it on the same page. Users can download the watermarked image by using the 'Save image as...' option. The resized image is saved in ...

What is the method for incorporating choices into a schema field in Mongoose?

If my Schema is like this: var fooSchema = new Schema({ foo: String }); and I'm looking to implement select: false for foo, how can I achieve this without altering the initial structure? var fooSchema = new Schema({ foo: { type: String, select: ...

Bidirectional communication between two AngularJS scopes or controllers utilizing a service

I am facing numerous situations where I require clicks or other interactions to trigger actions in a different area of the webpage (one-way communication). Now, I have encountered a need for bidirectional communication, where changes made in element A can ...

dc.js selects a chart that has already been rendered

I am attempting to manually adjust the width of a pie chart that has already been generated. The chart is constructed and displayed using an angular factory and directive, and I want to access this chart from a controller. Is there a method similar to var ...