Search through a Vue array to find distinct "Years" represented as strings, then create a new array where each element is a unique Year object key

Currently, I am working on creating a new array of objects that are sorted by year. Can someone suggest the most efficient method to iterate through an array of objects structured like this:

[
     {id: 42, count: 250, month: "January", year: 2024}
     {id: 37, count: 2023, month: "January", year: 2023}
     {id: 1, count: 1111, month: "January", year: 2022}
     {id: 2, count: 100, month: "February", year: 2022}
     {id: 3, count: 500, month: "March", year: 2022}
     {id: 6, count: 1, month: "April", year: 2022}
     {id: 8, count: 500, month: "May", year: 2022}

];

I want to transform it into a new array structured like this:

[
     {
       2024: [{id: 42, count: 250, month: "January", year: 2024}]
     },
     {
       2023: [{id: 37, count: 2023, month: "January", year: 2023}]
     },
     {
       2022: [
              {id: 1, count: 1111, month: "January", year: 2022},
              {id: 2, count: 100, month: "February", year: 2022},
              {id: 3, count: 500, month: "March", year: 2022},
              {id: 6, count: 1, month: "April", year: 2022},
              {id: 8, count: 500, month: "May", year: 2022}
           ]
      },
]

Answer №1

Utilizing forEach and find to organize data:

const data = [
     {id: 42, count: 250, month: "January", year: 2024},
     {id: 37, count: 2023, month: "January", year: 2023},
     {id: 1, count: 1111, month: "January", year: 2022},
     {id: 2, count: 100, month: "February", year: 2022},
     {id: 3, count: 500, month: "March", year: 2022},
     {id: 6, count: 1, month: "April", year: 2022},
     {id: 8, count: 500, month: "May", year: 2022}
]
const result = []
data.forEach(item => {
  let existing = result.find(res => item.year in res)
  if(existing) {
    existing[item.year].push(item)
  } else result.push({[item.year]: [item]})
})
console.log(result)

Answer №2

let data = [
     {id: 42, count: 250, month: "January", year: 2024},
     {id: 37, count: 2023, month: "January", year: 2023},
     {id: 1, count: 1111, month: "January", year: 2022},
     {id: 2, count: 100, month: "February", year: 2022},
     {id: 3, count: 500, month: "March", year: 2022},
     {id: 6, count: 1, month: "April", year: 2022},
     {id: 8, count: 500, month: "May", year: 2022}

];
let filteredData = []
data.forEach(item => {
    const obj = {}
    if(!filteredData.some(e => e[item.year])){
        obj[item.year] = data.filter(e => e.year == item.year)
        filteredData.push(obj)
    }
})
console.log(filteredData)

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

Inject the contents of an HTML file into a Vue div

Currently, I am utilizing jsfiddle to go through THIS {{respondedText}} <div>{{respondedText}}</div> But let's say I want to import HTML content from a file or website and then place it inside that div instead of showing "Event Rec ...

Begin the process of setting up PDF.js on the website

I've been attempting to incorporate PDF.js into my website, but I'm struggling to do it correctly. When I try to display the PDF file on the screen, I encounter this issue: https://i.sstatic.net/aixrP.png Although I can't see the PDF file ...

Increasing the size of elements with jQuery animate method

I've been utilizing the animate function in jQuery to dynamically resize a content area upon hovering over the element. Although the script is functioning correctly, I'm facing a challenge in preventing the script from resizing the content multi ...

Generating a fresh object derived from an existing object without saving any modifications

I am facing an issue with using an Array to store boilerplate objects that can be copied, modified, and added to another Array. The problem arises when the new Array takes ownership of the object, causing changes to persist in the original object. For exa ...

Is the Packery image grid only functional when the background image is specified in CSS and not in JavaScript? Perhaps we need to look into using Await/Sem

I've successfully implemented a packery image grid that is responsive and functional when the background image in the .item-content section is defined in the CSS file: http://codepen.io/anon/pen/eJdapq .item-content { width: 100%; height: 100%; ...

Running a Vue.js single-page application (SPA) in Docker without the need for N

The official Vue.js documentation features a straightforward example of dockerizing a single page application. You can find the example here. According to the documentation, the application will run on localhost:8080 Is it possible to bind the applicatio ...

Tips for dynamically resetting the dataTable

When I create a datatable and add rows dynamically based on the selected option, I encounter an issue where I need to reinitialize the dataTable every time the option is changed. To address this, I have placed the reinitialization code inside the $("#selec ...

Implementing styles from a constant file in React Native: A simple guide

In my file register.js, I have a UI component. import CustomHeader from '../components/Header'; ... static navigationOptions = ({navigation, navigation: { state } }) => { return { title: '', headerSty ...

Unable to access the done property in an AJAX JSON promise

Trying to dive into the world of JavaScript promises. My goal is to create a button that triggers a function displaying the result of a promise from another function. So far, I've been following tutorials and here's where I'm at: function my ...

Dividing the sentences inputted into a text area into an array and determining which sentence has been altered upon keyup

One of my current tasks involves handling the content within a textarea element: <textarea id="text"> Hello! Who am I? This is the third sentence. This, is another sentence. </textarea> Given that a textarea can be focused, I am seeking a met ...

Implement a jQuery DataTable using JSON data retrieved from a Python script

I am attempting to create an HTML table from JSON data that I have generated after retrieving information from a server. The data appears to be correctly formatted, but I am encountering an error with DataTable that says 'CIK' is an unknown para ...

Implement a javascript click action to alternate the visibility of an HTML element

Hey there! I'm a newcomer to Javascript and I'm currently working on a click function that will show an input element when a button is clicked, and hide it when the same button is clicked again. I've checked my console for error messages but ...

When it comes to AFrame+Three.js, which is more efficient: having numerous meshes with minimal triangles per mesh or having a few meshes with a high number of

Currently working with Aframe 1.0.4 and Three.js 111, I am exploring the performance differences between: Whether it is better to have a few entities with a high number of triangles or many entities with fewer triangles each. Specifically, I am debating ...

Guide to accessing the data within a glm::mat4

Trying to convert the values from a glm::mat4 matrix into a double[16] array. Any suggestions on how to approach this challenge? ...

Arranging elements in an array using a custom sorting function

I am in need of a custom user-defined function that can sort a multi-dimensional array in PHP. Below is an example of the array and the sorting function: <?php $multiDimArray = array( 49, 8, array( 'Muazam', ' ...

Sending File from React to Express Causes 404 Error

My current project setup involves a React application housed in a client folder and an Express server located in the root directory. Within the React app, there are functionalities for selecting files and submitting them. I aim to transfer these files from ...

Troubleshooting AngularJS: Resolving Issues with ng-model

Our website is experiencing issues with AngularJS functionality. Here's an example of the code we tested: register.html: <form name="register_form"> <ion-view view-title="Login" align-title="center"> <ion-content style="ba ...

Numerous unique designs paired with exclusive paths

I am working on setting up a system that accommodates multiple layout variations and includes private routes to display specific content based on the user's login status and assigned layout. Currently, I have three different layouts in place, with the ...

Tips for smoothly animating and showing content as the user scrolls to a specific element on the page

Here is a sample template: <template> <div id="Test"> <transition name="fade"> <div class="row" id="RowOne"> <p>Lorem ipsum dolor odit qui sit?</p> </div> ...

How to pass a PHP variable to JavaScript and ensure that the echo statement reflects any changes in the PHP variable

I am currently developing a script that dynamically generates a web page using data from my database. To achieve this, I have implemented a JavaScript function that is called when the page loads and whenever there is an update required. Initially, I succe ...