Forming an array that is categorized by year from a given array

I have a collection of data that needs to be grouped by year. There are 6 entries in this dataset, and I want to organize them into a two-dimensional array, with 2 entries for each year...

[4711.067999999985, 12596.399999999936, 12596.399999999936, "Accessories", "2011"]
[5277939.947800145, 8912342.140000183, 8912342.140000183, "Bikes", "2011"]
[16185.937500000333, 42468.34000000009, 42468.34000000009, "Accessories", "2012"]
[11725882.954398958, 19702448.459998813, 19702448.459998813, "Bikes", 2012]
[168010.80079996982, 448815.8899998886, 448815.8899998886, "Accessories", "2013"]
[14915767.767399808, 24907912.949997608, 24907912.949997608, "Bikes", "2013"]

The desired output should be an Array like...

Array[0][0] = [4711.067999999985, 12596.399999999936, 12596.399999999936, "Accessories", "2011"]

Array[0][1] = [5277939.947800145, 8912342.140000183, 8912342.140000183, "Bikes", "2011"]

Array[1][0] = [16185.937500000333, 42468.34000000009, 42468.34000000009, "Accessories", "2012"]

Therefore, Array[0] represents the year 2011, Array[1] represents 2012, Array[2] represents 2013, and so on.

Is there a way to iterate through the array and group the data by year?

Answer №1

Utilizing the JSON format to store your data is highly recommended, especially when working with JavaScript as an object. Below is an example of how it might appear:

{
  "years": [
    {
      "id": 2011, 
      "value01": 4711.067999999985, 
      "value02": 12596.399999999936, 
      "value03": 12596.399999999936, 
      "type": "Accessories"
    }, 
    {
      "year": 2012, 

      ...

    }
  ]
}

Alternatively, saving all values combined as a single string is not the most efficient solution for future use. More information on this topic can be found at w3schools.

Answer №2

let dataset = [ 
  [4711.067999999985, 12596.399999999936, 12596.399999999936, "Accessories", "2011"],
  [5277939.947800145, 8912342.140000183, 8912342.140000183, "Bikes", "2011"],
  [16185.937500000333, 42468.34000000009, 42468.34000000009, "Accessories", "2012"],
  [11725882.954398958, 19702448.459998813, 19702448.459998813, "Bikes", "2012"],
  [168010.80079996982, 448815.8899998886, 448815.8899998886, "Accessories", "2013"],
  [14915767.767399808, 24907912.949997608, 24907912.949997608, "Bikes", "2013"]
]

yearsList= ['2011', '2012', '2013']

groupedByYear = {}

yearsList.map((year, index) => {
  groupedByYear[index] = [];
  dataset.map(item => { 
    if(item.includes(year)){
      groupedByYear[index].push(item)
    }
  })
})

console.log("Data Grouped by Year", groupedByYear, "\n**********END\n\n")

// To get the data in a 2D array

let result = Object.values(groupedByYear)

console.log("Data for Year 2011", result[0]);
console.log("Data for Year 2012", result[1]);
console.log("Data for Year 2013", result[2]);

Answer №3

To efficiently tackle this problem with a complexity of O(n), consider using a hash table:

  let finalResults = [], hashTable = {};

  for(const [value1, value2, value3, category, year] of givenData) {
    if(!hashTable[year]) {
      finalResults.push(hashTable[year] = []);
    }
    hashTable[year].push([value1, value2, value3, category, year]);
 }

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

Executing multiple asynchronous calls in parallel in Node.js, with the ability to prioritize their

Imagine using Node.js to execute two asynchronous calls in order to retrieve some information. You could utilize the async package, where you simply pass two functions and an optional callback. async.parallel([fun1(){callback(null,1);}, fun2(){callback(nu ...

Display a list of years by iterating over a computed property in Vue JS

Currently, I have a code snippet that displays a list of years. It seems to me that this code is a bit excessive, and I believe that implementing a computed property for validYears would streamline the code and eliminate the need for unnecessary watchers. ...

The imported package is not functioning properly within the project

I've recently developed a Typescript Package and I want to test it in an application before publishing it on NPM. The main file (index.ts) of the package is structured like this => import Builder from './core/builder'; export default ...

What is the best way to mock a Hapi handler function?

I am attempting to mock a function from my route handler... Below is the route configuration: server.route({ method: 'GET', path: '/api/color/{format}', handler: this.pingLogic.getPing, config: { description: 'This is ...

Employing Isotope/jQuery for organizing posts on Tumblr in columns with the ability to infinitely scroll

Alright so, here we have the classic dilemma where scripts are running before images load. And to make matters more complicated, on Tumblr, there's no way to access image dimensions before they're loaded into the DOM... $('#thumbnails&apos ...

What is the best way to update all React components with a context without using a provider?

Considering this straightforward custom hook import React, { createContext, useContext } from 'react'; const context = { __prefs: JSON.parse(localStorage.getItem('localPreferences') || null) || {} , get(key, defaultValue = null) ...

Use vue.js to add a block of content after every sixth iteration in a loop

Currently, I have a list of offer cards rendering through a loop. I am adding a row div every 3rd column (bootstrap) element. Now, I need to also add another column element (banner block) for every 6th element in order to achieve a layout like the one show ...

Tips for showcasing content by hovering over buttons with the help of Bootstrap3 and Jquery

My code and fiddle are currently set up to display buttons when hovered over, but I want to modify it so that only the relevant button is displayed when a specific text is hovered over. For example, if "Water" is hovered over, only the button for Water sho ...

EJS variable not detected by Visual Studio IDE in JavaScript file

Working on a Node.js project with the express framework and utilizing EJS as the template engine, my IDE of choice is Visual Studio. Encountering an issue when using EJS variables within the same ejs file. Though it renders correctly and functions perfect ...

Using SetTimeout with the TextInput component in a React-Native application

Currently, I am working on creating a SearchBar component for my new Android application using React-Native. As a newcomer to React-Native, I created a function called _changeInput() to handle passing text to a local function. Initially, the text pass wor ...

What is the code to hide text once an HTML5 video has completed loading?

Is there a way to display "Video Loading" with a 75% opaque background over an HTML5 video, and then have both the text and background disappear once the video has finished loading? If so, how can I achieve this? Thank you for your time and effort! You ca ...

Eliminate a specific array from the firebase database

If I click on the delete button for item2, I want it to be removed from the list. { "items" : { "category1" : { "item" : { "0" : { "name" : "item1", }, "1" : { "name ...

Guide to placing content in a jQuery dialog box

When utilizing the $("#note_content").dialog() function, I am wanting to display the note_text content within the dialog box. Does anyone have suggestions on how this can be achieved? I want to ensure that the note_text is visibly displayed in the dialog ...

Using setInterval() does not automatically fetch JSON data at a specified interval for me

Attempting to constantly update the latitude and longitude coordinates from a dynamic API has proven to be a challenge. Despite utilizing jQuery with a set interval of 1000 milliseconds, the data retrieval from the API does not occur as expected. While i ...

Child class component unable to access React context value

Having some trouble with accessing a React context value in Employee.js that was set in App.js. It's not rendering correctly and I'm new to React. Any help would be appreciated. Thank you in advance. //index.js export const employeeContext = Rea ...

What methods can I use to display or conceal certain content based on the user's location?

I'm looking to display specific content exclusively to local users. While there are APIs available for this purpose, I'm not sure how to implement them. I'm interested in creating a feature similar to Google Ads, where ads are tailored base ...

I'm puzzled as to why this particular three.js demonstration isn't functioning properly

After installing three.js through npm using the command: npm install --save three, and setting up my files index.html and index.js in VS-Code, I encountered an issue. Despite copying a simple example from threejs.org, I couldn't get three.js to displa ...

Error: The variable "weather" is not defined while using React with the weatherbit API

I'm currently developing a React application that utilizes the Weatherbit API. However, I have encountered an issue with the weather object when calling my data array. Below is the code snippet where the problem occurs: import React from "react&q ...

Unable to retrieve form data through a POST request

After submitting the form data, I encountered an issue where 'req.file' and 'req.body.description' on the backend were returning 'undefined'. However, when I logged just 'req.body', the following was displayed: ---- ...

How can I modify the border color within a div element?

My journey into web development is just beginning, and I've grasped the basics of Java, JSP, HTML, JS, CSS, and JQ. However, I've hit a roadblock while attempting to change the border color of a div upon mouse hover. Despite my efforts, I haven&a ...