Convert an array of objects into a new array containing objects that are organized by their respective month and year

Hey, I'm facing an issue while trying to organize an array of objects by grouping them based on Month and Year. Although I have managed to transform the data and extract the necessary months and years, not all items are being correctly placed within their respective groups.

Below is my code snippet:

const data = [
  {text:"Lorem 1 ipsum", date:"Thu Feb 21 2019 11:44:24 GMT+0000 (GMT)"},
  {text:"Lorem 2 ipsum", date:"Thu Feb 21 2019 11:44:24 GMT+0000 (GMT)"},
  {text:"Lorem 3 ipsum", date:"Thu Mar 21 2019 11:44:24 GMT+0000 (GMT)"},
]
const texts = [];
const formattedData = data.reduce((acc, { date, text }) => {
  const dateObj = new Date(date);
  const monthYearFormat = dateObj
    .toLocaleString("en-us", { month: "long", year: 'numeric' });

  if(acc[monthYearFormat]) {
    texts.push(text);

    acc[monthYearFormat] = {
      text: texts
    }
  } else {
    acc[monthYearFormat] = {
      text: [text]
    }
  }

  return acc;
}, {})

console.log(formattedData)

The resulting output from this logic is:

{
  February 2019: {
   text: ['Lorem 2 ipsum']
  },
  March 2019: {
   text: ['Lorem 3 ipsum']
  }
}

It appears that my initial object is being replaced in the process. For instance, the group for February should also include "Lorem 1 ipsum" like so:

{
  February 2019: {
   text: ['Lorem 1 ipsum', 'Lorem 2 ipsum']
  },
  March 2019: {
   text: ['Lorem 3 ipsum']
  }
}

If you have any insights on where I might be going wrong, your help would be greatly appreciated. Thanks!

Answer №1

Why not change it up to

if(acc[monthYearFormat]) {
  texts.push(text);

  acc[monthYearFormat] = {
    text: texts
  }
}

To experiment, consider

if(acc[monthYearFormat]) {
  acc[monthYearFormat].text.push(text);
}

Answer №2

There are two different approaches to achieve the desired outcome. The second method is purely for amusement, utilizing the reduce function since it was used in your original code. Additionally, it's advisable to consider preserving the original object (entry in this scenario) so that not only the text but also the initial date can be retrieved if necessary.

const data = [
    { text: "Lorem 1 ipsum", date: "Thu Feb 21 2019 11:44:24 GMT+0000 (GMT)" },
    { text: "Lorem 2 ipsum", date: "Thu Feb 21 2019 11:44:24 GMT+0000 (GMT)" },
    { text: "Lorem 3 ipsum", date: "Thu Mar 21 2019 11:44:24 GMT+0000 (GMT)" },
];

let result = {};
data.forEach(entry => {
    let moyr = new Date(entry.date)
        .toLocaleString("en-us", { month: 'long', year: 'numeric' })
    result[moyr] = result[moyr] || { text: [] };
    result[moyr].text.push(entry.text);
});

console.log( result );

const data = [
    { text: "Lorem 1 ipsum", date: "Thu Feb 21 2019 11:44:24 GMT+0000 (GMT)" },
    { text: "Lorem 2 ipsum", date: "Thu Feb 21 2019 11:44:24 GMT+0000 (GMT)" },
    { text: "Lorem 3 ipsum", date: "Thu Mar 21 2019 11:44:24 GMT+0000 (GMT)" },
];

let result = data.reduce( (r,entry) => {
    let moyr = new Date(entry.date)
        .toLocaleString("en-us", { month: 'long', year: 'numeric' })
    r[moyr] = r[moyr] || { text: [] };
    r[moyr].text.push(entry.text);
    return r;
},{});

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

Connecting one property of a JavaScript object to another property within the same JavaScript object

I am working with a JavaScript Object and I want to use the map() function to match the Id with another id in the same JavaScript Object. Here is the schema for my JavaScript Object: var items = [ { BossId: "03", DateOfBirth: "1966-09-27T00:00:0 ...

Event scheduling with a calendar tool that automatically adjusts for overlapping events

Currently, I am working on developing a calendar system using PHP. For the week view, I aim to display events in a layout similar to iCal, where simultaneous events would adjust their width to half size. However, I am facing challenges in implementing thi ...

Plot data points from geojson onto a leaflet map using markers

How can I efficiently import geoJson data (containing over 2000 coordinates) into a leaflet map? Below is a brief snippet of geo json: { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { ...

Mock a single method within an Angular service

Within my Angular service, I have a method that listens for state changes and returns an observable. However, other methods within the same service handle transformation logic: ngOnInit() { this.isLoading = true; this.myService.stateListener().sub ...

Utilize a variable function in AngularJS

Within my app.js file, I have declared functions in the following manner: var func1 = function(v1,v2,v3) { . . } var func2 = function(v1,v2,v3) { . . } Moving on to my controller.js file: var action = ""; if(..) { action = 'func1';} ...

"Slow loading times experienced with Nextjs Image component when integrated with a map

Why do the images load slowly on localhost when using map, but quickly when not using it? I've tried various props with the Image component, but none seem to solve this issue. However, if I refresh the page after all images have rendered once, they ...

Confirmation dialog with user-defined button text

When the confirm prompt box is used, it typically displays "ok" and "cancel" buttons. I am looking to customize the label text for the buttons to read as Agree and Not Agree instead. If you have any suggestions on how to achieve this modification, please ...

Ways to track a moving div element using jQuery animations on the screen

I've been experimenting with animating a graphic along a curved path using jQuery.crSpline and I'm quite pleased with the outcome. The only issue is that the canvas size is intentionally set to be wider than most screens, causing the graphic to ...

Is there a node.js equivalent to Turbolinks available?

One of my favorite features in Rails is Turbolinks, as it enhances the user experience by making pages appear to load faster. Is there any alternative or similar functionality for node.js? ...

Tips for retrieving a specific key/value pair during an Http request in Angular

After making an HTTP call, I received a JSON file with the following data: [ { "totalConfirmed": 555, "mainlandChina": 548, "otherLocations": 7, "deltaConfirmed": 555, "totalRecovered": 0, "confirmed": ...

Next.js lacks proper Tree Shaking implementation for MUI

After setting up a react app with next.js, I noticed that the bundle size for the client significantly increased when importing MUI components. Specifically, there was a large module called @mui/base added to the bundle, even though I am only using three M ...

Unique custom babel plug-in - JSXElement traversal not supported

I'm currently in the process of creating my very own babel transform plugin. When I examine the AST for a React component using astxplorer.net, I notice that JSXElement appears in the tree as a node. However, when I attempt to log the path for the vi ...

Mastering Generic Types in Functions in Typescript

My current structure looks like this: export interface Complex { getId<T>(entity: T): string } const test: Complex = { getId<Number>(entity){return "1"} // encountering an error 'entity is implicitly any' } I am wondering w ...

What could be causing AngularJS to truncate my URL in the search bar?

Currently, I am in the process of setting up a state provider for a CRUD website. One issue I encountered is that when I navigate to www.mysite.com/posts/mypost, the URL gets shortened to www.mysite.com/mypost and does not trigger the controller as intend ...

Exploring error management in Vue3 and Vite when deploying to production

After following the error handler setup in the Vue documentation, I encountered a difference between using it on the development server and in production. The error handler effectively pinpointed the component and line number where the error occurred durin ...

What is the reason behind having the activator of strict mode as the string 'use strict'?

While many users may associate strict mode with the code 'use strict'; or "use strict";, the question arises as to why strict mode is not activated with an expression like use strict; instead. ...

Issue with ion-content on Ionic app not scrolling down when keyboard is displayed on an Android device

Currently, I am facing an issue with a basic view that contains a login form. When the keyboard pops up on Android devices, the content does not scroll up to ensure it remains visible above the keyboard. I have diligently followed the Keyboard instruction ...

What steps do I need to take in order to make the navbar-collapse function properly with an animated

After successfully implementing a collapsible navbar with a hamburger icon for mobile view, I decided to add some extra styling and animation to the hamburger button. However, now the hamburger button remains visible even in desktop view, which is not what ...

Pressing on an HTML element using JavaScript via the Selenium driver does not trigger the action

I'm attempting to use Selenium with Python to click on an element using JavaScript. Here's a snippet of my code: driver.execute_script("els=document.getElementsByClassName('buttons');\ for (var i = 0; i < els.length; i++) { ...

When using array.filter(), falsey values are excluded in a function expression, however, they are not excluded when using an arrow function

Currently, I'm tackling a challenge that involves the array_diff function, which aims to retrieve values from array a that also exist in array b. Having recently learned about the advantages of named function expressions for console debugging over an ...