Organize a Javascript array by grouping it based on a specific field and

I have an array that I need to group by the createdAt value.

 [
    {
      "createdAt": "2021-05-17T14:55:29.836Z",
      "machine": {
        "label": "MAQ_100",
      },
    },
    {
      "createdAt": "2021-03-10T13:22:45.694Z",
      "machine": {
        "label": "MAQ_33",
      },
    },
    ...
],

The desired output should be having the elements grouped based on their createdAt values.

[
    {"createdAtDates": ["17-05-2021"]}, 
    {"createdAtDates": ["10-03-2021","10-03-2021"]},
    ...
]

To achieve this, here is the logic implemented:

grouppedItems() {
     return this.items.reduce(function (groupedItems, item) {
       const groups = groupedItems.filter((el) => el.createdAt === item.createdAt);
       const found = groups.length === 1;
       const group = found ? groups[0] : { createdAt: item.createdAt, createdAtDates: [] };

       group.createdAtDates.push(item.createdAt);
       if (!found) groupedItems.push(group);

       return groupedItems;
     }, []);
},

items() {
     return this.connection
       ? 
         this.connection.values.map((item) => ({
           ...item,
           createdAt: formatDate(item.createdAt), //FORMAT DD-MM-YYYY
         }))
       : [];
   },

This function will result in the following structure:

[
    {
      "createdAt": "17-05-2021",
      "createdAtDates": ["17-05-2021"]
    },
    ...
]

The goal is to store only the formatted dates after reducing the initial array.

Answer №1

If you want to extract data from the items array and convert it into dd-mm-yyyy format, you can achieve this by using regex along with the reduce method for final result consolidation.

const items = [
  {
    createdAt: "2021-05-17T14:55:29.836Z",
    machine: {
      label: "MAQ_100",
    },
  },
  {
    createdAt: "2021-03-10T13:22:45.694Z",
    machine: {
      label: "MAQ_33",
    },
  },
  // Additional item objects ...
];

const result = items
  .map(({ createdAt }) => {
    return {
      createdAtDates: createdAt
        .split("T")[0]
        .replace(/(\d{4})-(\d{2})-(\d{2})/, "$3-$2-$1"),
    };
  })
  .reduce((acc, curr) => {
    const { createdAtDates } = curr;
    const isExist = acc.find((o) => {
      return o.createdAtDates[0] === createdAtDates;
    });
    if (isExist) {
      isExist.createdAtDates.push(createdAtDates);
    } else {
      acc.push({ createdAtDates: [createdAtDates] });
    }
    return acc;
  }, []);

console.log(result);

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

Triggering Submit Button Based on Checkbox Value in jQuery

Hey there, I'm encountering an issue. Let's say I have two types of checkboxes - one for person and one for company. If I submit the form without checking any of the person or company checkboxes, I want jQuery to display an alert. Otherwise, the ...

I'm unable to resolve all parameters for xxx -- unit testing using jest

I recently encountered an issue with a test in jest that is failing and displaying the following error message: Error: Can't resolve all parameters for LoginService: (?). at syntaxError (/Users/wilson.gonzalez/Desktop/proyecto_andes/external/npm/nod ...

Steps for showcasing a automated slideshow

I'm currently working on creating a slideshow that automatically displays multiple images. While the first image shows up just fine, it doesn't seem to transition to the next one. var currentSlide = 0; displaySlides(); functio ...

Quicker option for sorted array instead of np.where

If we have a large sorted array a, is there a quicker alternative to numpy's np.where for finding the indices where the values fall within a specific range? It seems like leveraging the sorted nature of the array could potentially improve efficiency. ...

Wait to fade in until the fade out process is completely finished

When I click on a button, the old box fades out and the new box fades in. However, I want to ensure that the .fadeIn() only happens once the .fadeOut() is complete. This will prevent two containers from being displayed simultaneously. Any suggestions on ...

Angular 2 encountering a memory exhaustion issue in the JavaScript heap

I am currently using Angular CLI and would appreciate it if you could verify my CLI information @angular/cli: 1.2.1 node: 6.10.0 os: win32 x64 @angular/animations: 4.1.1 @angular/common: 4.0.0 @angular/compiler: 4.0.0 @angular/compiler-cli: 4.0.0 @angular ...

"Exploring the process of integrating a controller into an external HTML file using AngularJS

I'm relatively new to AngularJS. In my web app, I have a set of buttons: index.html <button class="aButton">a</button> <button class="bButton">b</button> <script> $(document).ready(function(){ $(".aButton"). ...

What is preventing me from loading js and css files on my web pages?

I have developed a web application using SpringMVC with Thymeleaf and I am encountering an issue while trying to load javascript and CSS on my HTML5 pages. Here is a snippet from my login.html: <html xmlns="http://www.w3.org/1999/xhtml"> <head&g ...

Why does modifying a variable within the fetch URL result in undefined

I currently have a server running on the URL http://localhost:3000/. Within my JavaScript code, I have defined a variable called productCode with the value 'example-code55'. let productCode = 'example-code55'; const fetchData = async ...

What is the method for identifying which element in a zipped list has the highest quotient when dividing its paired values?

Hello everyone! I've encountered a problem that I need help with: I created a zipped list from two separate lists that I input like this: if __name__ == "__main__": data = list(map(int, sys.stdin.read().split())) n, capacity = data[0:2] v ...

Tips on invoking a Stencil component function or method from beyond the Vue instance

Is it possible to trigger a function in a Stencil component from the parent Vue instance? For example, I would like to call the callChild() method in the Vue instance, which will then trigger the doSomething() function in the Stencil component. The main ...

Remove duplicate JSON records in JavaScript by comparing and filtering based on identical attributes

Looking to remove duplicates from a JSON object [{id:1,name:a, cat:1},{id:1, name:a, cat:2},{id:2, name:b, cat:8}] I want to keep only the first occurrence of each duplicated id [{id:1,name:a, cat:1},{id:2, name:b, cat:8}] ...

Shifting and positioning the card to the center in a React application

I am currently constructing a React page to display prices. To achieve this, I have created a Card element where all the data will be placed and reused. Here is how it appears at the moment: https://i.stack.imgur.com/iOroS.png Please disregard the red b ...

A guide to showcasing items based on their categories using React.js

After successfully displaying Categories from a port (http://localhost:5000), accessing my MongoDB database, I encountered an issue when attempting to display the products for each category separately. Despite trying the same method as before, I keep rec ...

Issue with Material-UI NativeSelect not correctly displaying preselected option

I have the following code snippet: <NativeSelect classes={{ icon: classes.icon }} className={classes.select} onChange={this.onVersionChange} > { Object.keys(interface_versions).map(key => { return <optio ...

Ways to invoke a next.js api that implements next-auth programmatically

In my next.js app, I have integrated next-auth which is set up to allow authentication using Facebook and Google as providers. Additionally, there are some endpoints located in the pages/api folder of the app. These endpoints are accessed from standard ne ...

Having trouble getting the navigation function to work correctly for my ReactJS image slider

I am looking to create a simple image slider that contains 3 images in an array. I want to be able to navigate through the slider using just one function that can move back and forth between images. If you click "next" on the last image, it should bring ...

Stopping PHP execution when an Ajax request is aborted

I want the browser to wait for notifications, but stop waiting if a link is clicked. To achieve this, I have created a PHP script with a while loop that ends when an event occurs and then returns that event. PHP require 'required.php'; ignore_ ...

Unlimited scrolling: Fetching additional data via an Ajax request?

I am working on setting up a table with infinite scroll functionality to showcase user information such as name, address, and email. To accomplish this, I began by importing the json-server package and creating an API endpoint using fakerjs in a separate f ...

Revise the form used to edit data stored in Vuex and accessed through computed properties

My form component is used for client registration and editing purposes. Upon creation of the form component, I check if there is an ID in the URL to determine which type of form to display. If no ID is present (indicating a new client registration), all fi ...