Generate a fresh collection of objects all sharing a common identifier within a given array

Looking for help transforming this schedules array to match the desired output. Any ideas?

let schedules = [
 {day: 'Sunday', time: '5:00 PM'},
 {day: 'Monday', time: '4:00 PM'},
 {day: 'Monday', time: '12:00 PM'},
 {day: 'Tuesday', time: '1:00 PM'}
]

let output = [
 {day: 'Sunday', time: '5:00 PM'},
 [
  {day: 'Monday', time: '4:00 PM'},
  {day: 'Monday', time: '12:00 PM'}
 ],
 {day: 'Tuesday', time: '1:00 PM'}
]

Answer №1

To start, you can utilize the reduce() function to combine all objects into one and then use the map() function to extract an array of values.

let events = [
 {day: 'Sunday', time: '5:00 PM'},
 {day: 'Monday', time: '4:00 PM'},
 {day: 'Monday', time: '12:00 PM'},
 {day: 'Tuesday', time: '1:00 PM'}
]

var object = events.reduce(function(result, element) {
  if (!result[element.day]) result[element.day] = element
  else result[element.day] = Array.isArray(result[element.day]) ? result[element.day].concat(element) : [result[element.day]].concat(element)
  return result;
}, {})

var output = Object.keys(object).map(day => object[day])

console.log(output)

Answer №2

let meetings = [
 {day: 'Sunday', time: '5:00 PM'},
 {day: 'Monday', time: '4:00 PM'},
 {day: 'Monday', time: '12:00 PM'},
 {day: 'Tuesday', time: '1:00 PM'}
];
var calendar = {};
meetings.forEach(function(event){
   calendar[event.day] = calendar[event.day] === undefined ? event : Array.isArray(calendar[event.day]) ? calendar[event.day].concat([event]) : [calendar[event.day]].concat([event]);
})
var finalSchedule = Object.values(calendar);

console.log(finalSchedule);

Answer №3

Utilize the Reduce method to work with Object values

let appointments = [{
    day: 'Wednesday',
    time: '10:00 AM'
  },
  {
    day: 'Thursday',
    time: '9:00 AM'
  },
  {
    day: 'Thursday',
    time: '1:00 PM'
  },
  {
    day: 'Friday',
    time: '11:00 AM'
  },
  {
    day: 'Saturday',
    time: '2:00 PM'
  }
]


var data = appointments.reduce((accumulator, item) => {
  if (!accumulator[item.day]) {
    accumulator[item.day] = item
  } else if (Array.isArray(accumulator[item.day])) {
    accumulator[item.day].push(item);
  } else if (typeof accumulator[item.day] === 'object') {
    accumulator[item.day] = [accumulator[item.day]]
    accumulator[item.day].push(item)
  }

  return accumulator
}, {})

console.log(...Object.values(data))

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

JavaScript: Troubleshooting Array Formatting

Seeking assistance with formatting this JavaScript array accurately. It seems like I am overlooking something crucial: Javascript: <script type="text/javascript"> var dimensions = new Array("225","320","480", "--"); var walls = new Array() ...

Tips for incorporating a plugin and utilizing an external module or file on RT

My node.js application/module is currently functioning well with a plug-in concept. This means that my module acts like a proxy with additional capabilities, such as adding new functionality to the existing methods. To achieve this, follow these steps: Cl ...

The Ajax Auto Complete function encounters an issue when attempting to assign a value to the TextBox

I have a Textbox that utilizes an Ajax Autocomplete function. The function is functioning correctly and retrieves values from the database, populating them in the TextBox as well. However, there is a button on the page that triggers a query, fetching som ...

React Table Pagination Bug with Material UI Library

I am currently using Material UI and referencing the table sample provided at https://material-ui.com/demos/tables/. However, when attempting to implement the Custom Table Pagination Action according to the sample, I encountered an error. The error "inher ...

Retrieving PHP values from an array based on keys that are present in a separate array

I'm having difficulty with this task. I have two arrays. The first array, named colsArray, is a standard array structured as follows: Array ( [0] => fName [1] => lName [2] => city ) The second array, called query_data, is a mul ...

What is the best method for passing parameters from HTML to AJAX within code?

My project involves working with Flask, HTML, and Ajax. Here is the HTML code snippet: <script type=text/javascript> $(function() { $('a#calculate').bind('click', function() { $.getJSON('/_add_numbers&ap ...

Zooming on a webpage is causing problems

One issue I'm facing is with the elements on my page acting strange when I zoom in and out. Everything seems to be working fine except for a container div that should overlay a color over the image background. When I zoom in or switch to mobile view, ...

The webpack-bundle-analyzer tool reveals that running webpack -p does not eliminate the development dependency react-dom.development.js

Here is my custom webpack configuration: const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; const SO ...

What is the process for sending text messages in a local dialect using node.js?

Having an issue with sending bulk SMS using the textlocal.in API. Whenever I try to type a message in a regional language, it displays an error: {"errors":[{"code":204,"message":"Invalid message content"}],"status":"failure"} Is there a workaround for se ...

Exploring SVG Morphing Reversal Techniques in Anime.js

I have been trying to implement direction: 'reverse' and timeline.reverse(), but so far it hasn't been successful. Interestingly, when I set loop: true, the reverse animation can be seen within the loop. However, my goal is to trigger this a ...

Mastering the Material-UI Grid in SPAs: Conquering the Negative Margin Dilemma

While attempting to build a single page application (SPA), I've encountered an issue with using the Grid component from material-ui. Normally, I rely heavily on the Grid, but in this new project, something seems amiss. The current problem is evident ...

Trouble with Express.js and Mongoose: Issue with find() method not returning results for specified variable

For the task I'm working on, my goal is to display items that are only visible to the user who posted them. To manage sessions, I am using Passport.js. The code I have written seems to be functioning well up until the end. app.get('/latestp ...

Show me a list of all the commands my bot has in discord.js

Recently, I developed a Discord bot using discord.js and attempted to create a help command that would display all available commands to the user. For example, one of the commands is avatar.js module.exports.run = async(bot, message, args) => { le ...

Any ideas on how I can adjust this basic JSON to avoid triggering the "Circular structure to JSON" error?

Learning Journey I am currently teaching myself JavaScript and exploring JSON along the way. My current project involves developing a JavaScript WebScraper where I plan to store my results in JSON format. While I am aware of other methods like using data ...

Is there a way to verify the presence of a selector in Puppeteer?

How can I use Puppeteer to check if #idProductType exists and if not, assign producttype to ""? I have tried multiple solutions but none seem to work. const urls = [myurls, ...] const productsList = []; for (let i = 0; i < urls.length; i++) ...

Concealing specific sections of HTML content in a webview on the fly

I've been experimenting with a proof of concept feature to implement the ability to conceal certain parts of a web page loaded in a webview, but I seem to be encountering some issues... Within a UIWebview extension, I have something similar to this c ...

Identifying sluggish hardware or unresponsive browsers using JavaScript

My site features numerous CSS animations and transitions that run very slowly on specific browsers and older hardware. I want to avoid user-agent sniffing; is there a way to identify browsers or hardware configurations using JavaScript or a JS library, and ...

JavaScript Await Dynamic User Input

I have implemented a modified version of a script for generating random numbers in multiple columns of a spreadsheet, inspired by Tim Cooper's solution on stackoverflow. This script works by selecting a range of cells and running it from an onOpen men ...

Designing motion graphics for a browser game

As I delve into learning about Node.js, Angular.js, Socket.io, and Express.js, my current project involves creating a multiplayer poker game like Texas Hold 'Em. However, despite spending a considerable amount of time browsing the internet, I have bee ...

Jest fails to pass when encountering the double colon

Having issues testing a React app using Jest. I encounter errors when running my code: FAIL src\App.test.js ● Test suite failed to run C:/Users/user1/Projects/map-editor/src/App.js: Unexpected token (40:33) 38 | <div cla ...