Organize an array of objects based on their corresponding years

I am currently facing a challenge in grouping an array of objects by their respective years.

To provide some context, I have a visually appealing horizontal timeline graph created using D3js. My goal is to group events with overlapping dates by the year they occur in.

Here's an example of the data I am working with:

[
  {times: [{color: 'red', year: 2031}]},
  {times: [{color: 'green', year: 2031}]},
  {times: [{color: 'blue', year: 2031}]},
  {times: [{color: 'purple', year: 2045}]},
  {times: [{color: 'orange', year: 2045}]},
]

The desired output format should be as follows (events grouped by year):

[
  {times: [
    {color: 'red', year: 2031},
    {color: 'green', year: 2031},
    {color: 'blue', year: 2031}
  ]},
  {times: [
    {color: 'purple', year: 2045},
    {color: 'orange', year: 2045}
  ]}
]

I have attempted various approaches using reduce, but haven't been successful in achieving the required data structure:

data.reduce((result: any, current: any) => {
  const year = current.times[0].year;

  /* I'm unsure how to proceed with the 'year' variable at this point */
  result.push({ times: current.times[0] });

  return result;
}, [{ times: [{}] }]);

Could you offer guidance on the refactoring needed to attain the desired data format?

Answer №1

To optimize the array, you can search for the specific nested object based on the correct year.

var data = [{ times: [{ color: 'red', year: 2031 }] }, { times: [{ color: 'green', year: 2031 }] }, { times: [{ color: 'blue', year: 2031 }] }, { times: [{ color: 'purple', year: 2045 }] }, { times: [{ color: 'orange', year: 2045 }] }],
    result = data.reduce((r, { times: [data] }) => {
        var temp = r.find(({ times: [{ year }] }) => year === data.year);
        if (temp) temp.times.push(data);
        else r.push({ times: [data] });
        return r;
    }, []);

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

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

iOS Error: Array index exceeds range

Hi everyone, I've encountered an issue with the error message 'array index out of range'. I'm fetching JSON data from the web and converting it into an array. While loading comments, I have not found a related question to my problem. I ...

Rendering various models in separate DIVs using Threejs

(Brand new to venturing into Three.js) Overview Currently, I am immersed in the development of a 3D Viewer that can showcase multiple stl models simultaneously. Each model is supposed to be rendered within its own separate div element, resulting in a g ...

Slowly introduce a sequence of divs, then smoothly fade out the div that came before

After successfully using jQuery to create a smooth fade-in effect for a series of divs, I am now looking to incorporate a fade-out transition for the previous div. My plan is to include a fade out function as a callback within the existing fade in function ...

Encountering net::ERR_CONNECTION_RESET and experiencing issues with fetching data when attempting to send a post request

I am facing a React.js task that involves sending a POST request to the server. I need to trigger this POST request when a user clicks on the submit button. However, I keep encountering two specific errors: App.js:19 POST http://localhost:3001/ net::ERR_CO ...

I am trying to populate my React hook form with existing data so that I can easily make updates to my task

I am struggling with prefilling my react hook form. Currently, I am seeing [object Object],[object Object],[object Object],[object Object],[object Object] in my input field. Can anyone help me understand how to extract the content of the object to automat ...

Using the Jquery load function to add new content to existing HTML

I'm attempting to create an AJAX request that will insert additional HTML content into the existing content within specified tags. Below is the structure of my load function. <script> $(document).ready(function(){ $(".tid-select").cha ...

Using Javascript to retrieve information from an API and display the results

Currently, I am working on developing a Chrome plugin that involves querying the Alexa API with the current URL of the browser to determine if it falls within the top 100,000 sites. While I initially had a Python solution in place for this task, my focus n ...

Set a variable equal to the output of an external function, but receive an undefined value in

I've been facing an issue where I'm trying to store the value of an external function in a JavaScript variable, but it keeps returning undefined. The external function in question is designed to search for a specific record within a database: f ...

"Trouble arises when attempting to render a basic Vue.Draggable component within a nested ul

Problem with Nesting After receiving feedback from @Amaarrockz, I attempted to create a sandbox to address the issue I'm facing. However, the problem persists. Here's the code snippet: <div id="app"> <ul> <li ...

Delete elements from a dynamic list

I am working with a dynamic array containing chat messages, structured like this: { id:1, message: bla-bla }, { id:2, message: bla-bla }, { id:1, message: bla-bla }, { id:1, message: bla-bla }, { id:3, message: bla-bla }, { id:4, message: bla- ...

Implementing Google Apps Script code on my webpages

I am currently in the process of developing a web application using HTML, CSS, and JavaScript with Google Spreadsheet serving as my database. To turn this web app into a fully functional application, I am considering utilizing PhoneGap. After successfully ...

Automatically populate a dropdown list based on the selection made in another dropdown menu

I'm populating a second textbox based on the input of the first textbox in auto.jsp. Now, I want to automatically populate a combo box as well. How can I achieve this? Specifically, I want to autofill the second combo box based on the selection made i ...

Safari not updating Angular ng-style properly

I created a simple carousel using Angular and CSS animations which works well in Chrome. However, I recently tested it in Safari and noticed that the click and drag functionality does not work. I've been trying to fix this issue for days and could use ...

PHP-based LESS compiler

Is there a way to compile LESS from PHP without using node.js or ruby? I came across a PHP implementation called LESSPHP on Google, but it seems outdated and doesn't support newer features. Would using the V8js API to run less.js work, even though i ...

Is there a way to assign a unique scrollTop value for a specific scrollspy location?

I have a custom script that tracks the current position within a menu and applies an active class to it. However, I require specific rules for the ID contact_form. Specifically, I need to add 1000px to the scrollTop value for that particular ID location. ...

Steps for producing an interactive Material UI Icon Atom in StoryBook and React TypeScript

I have integrated StoryBook with React, TypeScript, and Material UI. My goal is to create a dynamic Icon Atom component that can render different icons based on the props passed to it. Currently, I am facing issues with my current approach. Specifically: ...

The android webview is having trouble loading HTML that includes javascript

I have been attempting to showcase a webpage containing HTML and JavaScript in an android webview using the code below. Unfortunately, it doesn't seem to be functioning properly. Can someone provide assistance? Here is the code snippet: public class ...

Firing a custom jQuery event when a page loaded via AJAX is complete, ensuring it is triggered

I am facing an issue with a particular scenario. There is a page that contains a script to load a child page and log a custom event, which is triggered in a Subform. --Index.html-- <body> <input type="button" class="clickable" value="Load child ...

Exploring the use of single character alternation in regex with Webstorm's Javascript Regex functionality

I've been attempting to divide the string using two different separators, like so: "some-str_to_split".split(/-|_/) It successfully splits the string based on both "-" and "_". However, Webstorm is issuing a warning: Single character alternation ...

Javascript: Dynamically Altering Images and Text

One feature on my website is a translation script. However, I'm struggling to activate it and update the image and text based on the selected language. This is the code snippet I am currently using: <div class="btn-group"> <button type ...