Guide on how to arrange data into subarrays based on a specific field in JavaScript

I have an array of data that I need to group by day in order to create a new structure. The input array is as follows:

input_array = [{
  "name": "alagu",
  "day": "monday",
  "time": "morning",
  "task": "studying"
}, {
  "name": "alagu",
  "day": "sunday",
  "time": "evening",
  "task": "playing"
}]

The desired output should look like the following array format:

result_array = [{
  "name": "alagu",
  "day": "monday",
  "schedule": [
    { "time": "morning", "task": "studying" }
  ]
}, {
  "name": "alagu",
  "day": "sunday",
  "schedule": [
    { "time": "evening", "task": "playing" }
  ]
}]

In essence, I need to group the data by day and then organize it into sub arrays containing elements for time and task. Any assistance would be greatly appreciated.

Answer №1

To achieve the desired outcome from the provided sample data using the foreach and map functions:

const input_data = [{ "name":"alagu", "day":"monday", "time":"morning", "task":"studying" }, 
               { "name":"alagu", "day":"monday", "time":"evening", "task":"playing" },
               { "name":"alagu", "day":"monday", "time":"night", "task":"sleeping" },
               { "name":"alagu", "day":"sunday", "time":"morning", "task":"playing" },
               { "name":"alagu", "day":"sunday", "time":"evening", "task":"playing" }, 
               { "name":"alagu", "day":"sunday", "time":"night", "task":"sleeping" }]

const final_result = {};

input_data.forEach(item => {
    const { name, day, time, task } = item;
    if (!final_result[day]) {
        final_result[day] = { name, day, event_list: [] };
    }
    final_result[day].event_list.push({ time, task });
});

const result_set = Object.keys(final_result).map(key => final_result[key]);

console.log(result_set);

Outcome :

[
   {
      "name":"alagu",
      "day":"monday",
      "event_list":[
         {
            "time":"morning",
            "task":"studying"
         },
         {
            "time":"evening",
            "task":"playing"
         },
         {
            "time":"night",
            "task":"sleeping"
         }
      ]
   },
   {
      "name":"alagu",
      "day":"sunday",
      "event_list":[
         {
            "time":"morning",
            "task":"playing"
         },
         {
            "time":"evening",
            "task":"playing"
         },
         {
            "time":"night",
            "task":"sleeping"
         }
      ]
   }
]

Answer №2

To implement the reduce method, you can follow this example:

const inputData = [{
  "username": "john_doe",
  "day": "monday",
  "time": "morning",
  "task": "coding"
}, {
  "username": "john_doe",
  "day": "monday",
  "time": "evening",
  "task": "reading"
}, {
  "username": "john_doe",
  "day": "tuesday",
  "time": "night",
  "task": "sleeping"
}, {
  "username": "john_doe",
  "day": "wednesday",
  "time": "morning",
  "task": "exercising"
}]

const outputData = Object.entries(inputData.reduce((acc, cur) => {
  return {
    ...acc,
    [cur.day]: cur.day in acc ? [...acc[cur.day], cur] : [cur]
  }
}, {})).map(([key, value]) => ({
  name: value[0].username,
  day: key,
  plans: value.map(val => ({
    time: val.time,
    task: val.task
  }))
}))

console.log(outputData)

Answer №3

const tasks = [{"name":"John","day":"Monday","time":"morning","task":"studying"},{"name":"John","day":"Monday","time":"afternoon","task":"playing"},{"name":"John","day":"Tuesday","time":"night","task":"sleeping"},{"name":"John","day":"Sunday","time":"morning","task":"running"},{"name":"John","day":"Sunday","time":"evening","task":"painting"}]

let scheduleByDay, result = [...new Set(tasks.map(item=>item.day))]
  .map(day=>(scheduleByDay=tasks.filter(item=>item.day===day),
    {name: scheduleByDay[0].name, day, activities: scheduleByDay.map(({name, day, ...rest})=>rest)}))

console.log(result)

Answer №4

A new feature I would like to suggest is a universal groupBy() function that facilitates grouping a collection based on a specific key.

function groupBy(iterable, fn) {
  const groups = new Map();
  for (const item of iterable) {
    const key = fn(item);
    if (!groups.has(key)) groups.set(key, []);
    groups.get(key).push(item);
  }
  return groups;
}

Using this function allows us to categorize data by:

const groups = groupBy(input_array, item => JSON.stringify([item.name, item.day]));

The choice to use JSON.stringify() is deliberate as two arrays are considered equal only if they reference the same array. Thus, creating a new array instance like [item.name, item.day] will never match an existing key. Serializing the array using JSON allows comparison between strings instead, making the process feasible.

// normal array comparison
["alagu", "monday"] === ["alagu", "monday"] //=> false

// serialized (using JSON) array comparison
'["alagu","monday"]' === '["alagu","monday"]' //=> true

Once the data is grouped, the structure of groups appears as follows:

// displaying Map instance contents in object notation
Map{
  '["alagu","monday"]': [
    { name: "alagu", day: "monday", time: "morning", task: "studying" },
    { name: "alagu", day: "monday", time: "evening", task: "playing"  },
    { name: "alagu", day: "monday", time: "night"  , task: "sleeping" },
  ],
  '["alagu","sunday"]': [
    { name: "alagu", day: "sunday", time: "morning", task: "playing"  },
    { name: "alagu", day: "sunday", time: "evening", task: "playing"  },
    { name: "alagu", day: "sunday", time: "night"  , task: "sleeping" },
  ],
}

To convert this into an array, we can utilize Array.from(groups) and provide custom transformations through map().

const result_array = Array.from(groups).map(([json, items]) => {
  const [name, day] = JSON.parse(json);
  const schedule = items.map(({ time, task }) => ({ time, task }));
  return { name, day, schedule };
});

In the above implementation, the serialized key is decoded back into its original JavaScript form using JSON.parse(), enabling retrieval of the name and day values of each group.

The next step involves transforming items, an array containing all properties, into objects with only time and task attributes.

.map(({ time, task }) => ({ time, task }))
achieves this goal efficiently, combining object destructuring with property shorthand syntax.

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

What are the potential reasons for a function in React not being identified as a function?

I recently started learning React and decided to follow this YouTube tutorial on creating a TO DO LIST using React. https://www.youtube.com/watch?v=E1E08i2UJGI Everything seems to be in place, but when I try to interact with my form by typing something an ...

Unable to transform the object into a primitive value when converting it to a URL encoded string

I am attempting to convert an object into a URL encoded string using the following functions: console.log(jQuery.param($scope.employee)); console.log($.param($scope.employee)); However, they are giving me an error: TypeError: Cannot convert object to ...

Moving Configuration Files in NextJS

When working on a typical Next.js project, I often end up with several root-level configuration files: tsconfig.json next.config.js next-seo-config.ts .eslintrc etc... I am looking to tidy up my root directory by moving these files into their own separat ...

Gulp halts when watching code and reloads upon any changes made

Hey there, I'm new to GULP and could use some help... I've been trying to configure GULP for a template that uses AngularJS. When I run the gulp command, the console displays the message "**Done Waching code and reloading on changes" but nothing ...

Rearrange the position of the customized google map marker to appear just above the latitude

Can you provide guidance on how to move a customized Google Map marker above a specific latitude and longitude point? You can view the code structure in this JSBIN: Link. I have used three object arrays for reference. Where should I insert the "anchor" i ...

How to eliminate unnecessary space when the expansion panel is opened in material-ui

Is there a way to eliminate the additional space that appears when clicking on the second accordion in material UI? When I open the second accordion, it shifts downward, leaving a gap between it and the first accordion. Any suggestions on how to remove thi ...

Mobile site's call button functionality is malfunctioning

For the telephone number on my mobile site, I employed the <a href="tel:+1800229933">Call us free!</a> code. However, it seems to be malfunctioning on several devices. Any insight on this issue would be greatly appreciated. Thank you. ...

Discovering an Improved Method for Implementing a Functional jQuery Menu Bar

Currently, I have a functioning Menubar where each button on the menu triggers a secondary Menubar using jQuery. The code snippet is as follows: <script> $(document).ready(function(){ $("#homeButton1").mouseover(function(){ $(".secondMen ...

Verifying the functionality of a m3u8 URL with Javascript

I have been using the following code to check if an m3u8 URL is broken or not. I tried with two different URLs, one that is live and one that is offline. However, my javascript function does not alert me whether the file exists or not. There are no errors ...

Effortlessly initiate the consecutive playback on SoundCloud

I'm currently working on my music blog and I'm looking for some guidance in implementing a feature where the widgets start playing one after the other. Specifically, I have both SoundCloud and YouTube widgets, but I would like to focus on achievi ...

Comparing PHP's STRCHR with the equivalent function in JavaScript

Does anyone know if there is a similar function in JavaScript to strchr in PHP? I could use some assistance. Thank you! ...

What is the best way to populate an AngularJS list using a for loop or an array?

After reviewing this code that has been hard coded, I have identified the following: $scope.years = [ {id:curryear, name: curryear} {id:curryear - 1, name: curryear - 1} {id:curryear - 2, name: curryear -2} ]; My current task involves populating ...

Storing the values of a React JS application in local storage using

Storing data received from the backend in local storage: async onSubmit(e){ e.preventDefault(); const {login, password } = this.state; const response = await api.post('/login', { login,password }); const user ...

Discover the procedure for extracting a dynamic value from JavaScript to PHP

Could the centerId value be utilized and transferred to a php variable? const data = { action: 'ft-add-member', maritalStatus: $('.ft-entry-relationship-info .ft-marital-status ul li.current a').data('dropdown' ...

Using this.el.object3D.position.set(0,0,0) may not function correctly unless a breakpoint is placed in the debugger beforehand

I am trying to attach a door element to the Vive controller's blue box element. Once the door is appended, I attempt to set its position to '0 0 0' using the code "this.el.object3D.position.set(0,0,0)" in order to connect it to the blue box ...

Modifying the value of a local variable results in a corresponding adjustment to the original global variable's value

Within my Node.js program, I have set up an array named "list" in the routes section. This array is populated with values from a function defined in the model. The code for this route looks like: var express = require('express'); var router = ex ...

Quick question about utilizing Ajax with spans

<span name = "menu"> <!-- javascript here --> <!-- content loaded via ajax --> </span> <span name = "content"> <!-- content loaded via ajax --> <!-- updated by buttons from the menu--> </span> Seeking a ...

Updating HighCharts with fresh data through Ajax

I'm currently in the process of replacing the highcharts that I initially loaded through ajax. The idea is to obtain new values from the user, pass them via Ajax, and then display an entirely new graph (with a different type and data). Here's wha ...

jQuery - "Error: fadeIn is not a valid function"

Encountering an odd issue here. Attempting to execute fadeIn() but receiving the error ".fadeIn is not a function". Here is my code: body { display:none; } <!DOCTYPE html> <html lang="en> <head> <!-- Required meta tags --&g ...

Modify the width measurement from pixels to percentage using JavaScript

Looking for some help with a content slider on my website at this link: . I want to make it responsive so that it adjusts to 100% width. I managed to make it responsive by tweaking some code in the developer tools, but now I'm stuck. The bottom two p ...