Javascript: transforming an array from another

In my Firebase array-snapshot, I have entries for my application that include a "referenceDate" timestamp:

entry [0] { referenceDate: 2017-08-03,...
entry [1] { referenceDate: 2017-08-02,...
entry [2] { referenceDate: 2017-08-01,...
entry [3] { referenceDate: 2017-07-03,...
entry [4] { referenceDate: 2017-07-02,...

I am looking to group these entries by month and year with the following format:

08.2017
03.08.2017
02.08.2017
01.08.2018
07.2017
03.07.2017
02.07.2017

My approach is to create a nested array structure like this:

{"monthYear": "08.2017":[
    {"referenzDatum": 2017-08-03},... },
    {"referenzDatum": 2017-08-02},... },
    {"referenzDatum": 2017-08-01},... },]},
 {"monthYear": "07.2017":[
    {"referenzDatum": 2017-07-03},... },
    {"referenzDatum": 2017-07.02},... }, ...]}

I then plan to loop over this structure using two ngFor loops to generate the HTML output.

Does anyone have a more efficient way to achieve this? The code snippet I tried doesn't scale well beyond a few different months and looks messy.

Answer №1

If you're looking to achieve this sort of functionality, one common approach is to use the groupBy method. While Javascript's Arrays don't have a built-in groupBy function, third-party libraries like underscore.js offer solutions. Alternatively, you can create your own implementation using reduce:

let getMonthYear = (obj) => obj.date.split('-').reverse().slice(1).join('.');

let groupBy = (array, fn) => array.reduce(function(groups, item) {
       let key = fn(item)
       if (!groups[key]) groups[key]=[]
       groups[key].push(item)
       return groups;
   }, {});

let entries = [ { date: '2017-08-03' },
                { date: '2017-08-02' },
                { date: '2017-08-01' },
                { date: '2017-07-03' },
                { date: '2017-07-02' } ]
let groups = groupBy(entries, getMonthYear);
console.log(groups)

This code snippet will yield the following result:

{ '08.2017': 
   [ { date: '2017-08-03' },
     { date: '2017-08-02' },
     { date: '2017-08-01' } ],
  '07.2017': 
   [ { date: '2017-07-03' },
     { date: '2017-07-02' } ] }

For more information on similar topics, check out this related question.

Answer №2

 const dateArray = [
      {'referenceDate':'2018-10-01'},
      {'referenceDate':'2018-09-30'},
      {'referenceDate':'2018-09-29'},
      {'referenceDate':'2018-08-31'},
      {'referenceDate':'2018-08-30'}
   ];
  const finalResult = [];

dateArray.forEach(function(record) {
    const newDate = new Date(record.referenceDate);

    const dayValue = newDate.getDate();
    const monthIdx = newDate.getMonth() + 1;
    const yearValue = newDate.getFullYear();

    const customDateFormat = monthIdx+'.'+yearValue;

    if(!(customDateFormat in finalResult)) {
        finalResult[customDateFormat] = [];
    }
    finalResult[customDateFormat].push(record);
});

Answer №4

One approach could be to utilize a hash table:

let schedule = {};

data.forEach((element) => {
  let date = new Date(element.referenceDate),
  year = date.getFullYear(),
  month = date.getMonths() + 1;

  if (!schedule[year]) schedule[year] = [];
  if (!schedule[year][month]) schedule[year][month] = [];

  schedule[year][month].push(element);
});

Subsequently, you can retrieve all available years, arrange them in order, and present them:

Object.values(schedule).sort((x, y) => x - y).forEach((year) => {
  console.log(year);
  for (let [month, entries] of schedule[year].entries()) {
     console.log(month, entries.join("\n"));
  }
});

Answer №5

Give this a shot:

const data = [{ date: '2017-08-03'}, { date: '2017-08-02'}, { date: '2017-08-01'}, { date: '2017-07-03'}, { date: '2017-07-02'}]; 
const finalData = {};

for (var i = 0; i < data.length; i++) {
  const month = data[i].date.substring(0, 7).split('-').reverse().join('.');
  if (!finalData[month]) {
    finalData[month] = [];
  }
  finalData[month].push(data[i]);
}

const outputElement = document.getElementsByClassName('json')[0];
outputElement.innerHTML = JSON.stringify(finalData, undefined, 2);
<pre class="json"></pre>

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

Rotate the image using the handler, not by directly manipulating the image itself

I need help rotating the image using a handler instead of directly on the image itself. I do not want to rotate the image when clicking and rotating it directly. Please do not suggest using Jquery UI rotatable because resizing the image with Jquery UI resi ...

How can we eliminate special characters from arrays stored in a PostgreSQL table?

I have a column named 'directedlink_href' in a database table that holds arrays starting with the '#' character. How can I remove the '#' character from all values within these arrays? For example... {#osgb4000000030451486, ...

Arranging particular components within jstree

Is it possible to use the "sort" plugin from jstree to sort specific elements only and not all nodes? Here's what I have tried so far: $('#container').jstree({ "plugins" : ["sort"] }); <script src="https://ajax.googleapis.com/ajax/l ...

Form a triangle in order to prevent the inner content from spilling out

I'm currently attempting to design a triangle shape that prevents the inner content from overflowing while still allowing the inner content to be draggable. So far, I have experimented with various solutions such as polygons and canvas, but none of t ...

Modify the style of a webpage through JavaScript

Need help with calling a JS event based on button presses and changing CSS font styling accordingly for each button? Check out the code snippet below: body { background-image: url("back2.jpg"); background-size: 100% 100%; } ...

Images on web pages are automatically resized to fit into a smaller preview window

Currently, I am facing an issue with the display of images in my grid windows on my website . The images are appearing as partial representations instead of rescaled versions where the whole picture is resized to fit the grid window. I have attempted mod ...

Exploring the keyof operator in Typescript for object types

Is there a way to extract keys of type A and transfer them to type B? Even though I anticipate type B to be "x", it seems to also include "undefined". Why does the keyof operator incorporate undefined in the resulting type? It's perplexing. I kn ...

What is the best way to fetch all the orders from my product schema using response.send?

This is my custom Product schema const productSchema = new mongoose.Schema({ title: { type: String, required: [true, "Title is required"] }, details: { type: String, required: [true, "Details are r ...

Preserve present condition following a jQuery click event

I'm facing a challenge where I need to hide a button upon clicking another button, but the problem is that when the page refreshes, the hidden button becomes visible again. My objective is to keep it hidden even after refreshing the page and only reve ...

Developing a feature to organize content by categories and implement a functionality to load more data efficiently using NodeJS routes

I am looking to develop a system that limits the number of displayed posts and includes a "load more" button to retrieve additional posts from where the limit was previously reached. Additionally, I want to implement the functionality to change the orderin ...

Having difficulty accessing the API response accurately

The response from my API is as follows: {"__v":0,"short":"8xdn4a5k","_id":"5404db5ac27408f20440babd","branches":[{"version":1,"code":""}],"ext":"js","language":"javascript"} When I use this code, it works perfectly: console.log(response.short); However ...

Difficulty with Nuxt + Vuex: Retrieving data from state using getter

Can anyone assist me with this issue? I am having trouble with my getters in Vuex not recognizing the state. Here is the code snippet: https://codesandbox.io/s/crazy-moon-35fiz?file=/store/user.js user.js: export const state = () => ({ user: { is ...

When applying Bucket Sort to an array sorted in reverse order, the program encounters an ArrayIndexOutOfBoundsException

In order to run an array that is sorted in reverse order (e.g. 100, 99, 98, 97...3, 2, 1, 0 - highest to lowest) through a bucket sort that will rearrange it from lowest to highest, the following code is used: int n = 100; // Determines the size of the arr ...

Struggling to eliminate placeholders using regular expressions in JavaScript

In my dynamically generated table, I have some placeholders that need to be removed. These placeholders are in the format of {firm[i][j]}, where i and j are numbers. I attempted to use a regular expression in JavaScript to remove them, but it didn't ...

Incorporating a different moment locale may disrupt the original date format

There's a strange issue with the moment library that I can't seem to figure out: I have this date: Wed Feb 28 2018 16:24:37 GMT+0100 (CET) But when I add import 'moment/locale/fr';, the same date changes to Sun Jan 28 2018 16:24:37 GM ...

Mixing together an array of colors, experimenting with adding a touch of transparency

Here is my first question, diving right in. I recently created a canvas in HTML and followed a tutorial to generate random floating circles that interact with the mouse position......if you want to check it out, click here. The issue I'm facing now ...

Disabling the Annoying Video Popup Ad that's Blocking my "Load More" Feature in Selenium

I am currently in the process of scraping around 1000 URLs using Selenium, and I am very close to getting it to work smoothly. Each URL contains a "load more" button that I keep clicking until a Stale Element exception is thrown, which I handle. Everything ...

The length of the HTTP response in Angular is not defined

Currently, I am utilizing Angular in conjunction with jQuery Mobile to develop multiple pages, but I have encountered an obstacle when using the $http service to connect to my JSON requests. While populating a few arrays with functions and successfully ret ...

When selecting an input within a div, the Angular onblur function is behaving erratically

How can I prevent the div from closing when I click on an input inside it after setting a tabindex to the div and closing it on blur? Solution for app.component.html: <button (click)="openToggle('toggle1')">Toggle 1</button> ...

Developing an SQL table for a website using JavaScript

My command is not functioning as expected and I am struggling to identify the issue. The database opens successfully, however, it fails to process the table creation. var createtable2 = 'CREATE TABLE IF NOT EXISTS offlineCabinDefects (id INTEGER PRIM ...