Categorize information within an array based on specific attributes

My goal is to have nested data organized by the day number.

Here is an array example that I want to group using the lodash plugin.

[{
  "Pnl": 29.0035635,
  "date": ""11/14/2022",
  "dayNumber"" : 1,
  "translationDayOfWeek": "Monday"
},
{
  "Pnl": 50.8878545,
  "date": "11/08/2022",
  "dayNumber"" : 2,
  "translationDayOfWeek": "Tuesday"
},
{
  "Pnl": 73.1014552,
  "date": "11/08/2022",
  "dayNumber" : 2,
  "translationDayOfWeek": "Tuesday"
},
{
  "Pnl": 32.477,
  "date": "11/08/2022",
  "dayNumber : 6,
  "translationDayOfWeek":"Saturday"
},
{
  "Pnl"": 25.43999561,
  "date": ""09/30/2022",
  "dayNumber"": 5,
  "translationDayOfWeek": ""Friday"
},
{
  "Pnl"": 17.6294068,
  "date": ""09/30/2022",
  "dayNumber ": 1,
  "translationDayOfWeek"" : "Monday"
}]

This is what I expect for an output:

[
  {
    "dayNumber": 1,
    "orders":[
      {
        "Pnl": 29.0035635,
        "date": "11/14/2022",
        "dayNumber": 1,
        "translationDayOfWeek": "Monday"
      },
      {
        "Pnl": 17.6294068,
        "date": "09/30/2022",
        "dayNumber": 1,
        "translationDayOfWeek": "Monday"
      }
    ]
  },
  {
    "dayNumber": 2,
    "orders": [
      {
        "Pnl": 50.8878545,
        "date": "11/08/2022",
        "dayNumber": 2,
        "translationDayOfWeek": "Tuesday"
      },
      {
        "Pnl": 73.1014552,
        "date": "11/08/2022",
        "dayNumber": 2,
        "translationDayOfWeek": "Tuesday"
      }
    ]
  }
]

I attempted the solutions provided in a Stack Overflow post, but it did not yield the desired result for me.

Answer №1

When utilizing Loadsh library, here is a snippet of code you can use to group elements in an array:

const arr = []; //your array
_.map(
    _.groupBy(arr, function (obj) {return obj.dayNumber}),
    (groupedItems,index) => ({dayNumber: index, items: groupedItems})
)

Answer №2

The code snippet provided demonstrates how grouping can be achieved using the reduce() method.

const data = [{
  "Pnl": 29.0035635,
  "date": "11/14/2022",
  "dayNumber": 1,
  "translationDayOfWeek": "Monday"
},
{
  "Pnl": 50.8878545,
  "date": "11/08/2022",
  "dayNumber": 2,
  "translationDayOfWeek": "Tuesday"
},
{
  "Pnl": 73.1014552,
  "date": "11/08/2022",
  "dayNumber": 2,
  "translationDayOfWeek": "Tuesday"
},
{
  "Pnl": 32.477,
  "date": "11/08/2022",
  "dayNumber": 6,
  "translationDayOfWeek": "Saturday"
},
{
  "Pnl": 25.43999561,
  "date": "09/30/2022",
  "dayNumber": 5,
  "translationDayOfWeek": "Friday"
},
{
  "Pnl": 17.6294068,
  "date": "09/30/2022",
  "dayNumber": 1,
  "translationDayOfWeek": "Monday"
}];

let grouped = data.reduce((acc, el) => {
  let dayNumber = el.dayNumber;
  acc[dayNumber] ??= { dayNumber, orders: [] };
  acc[dayNumber].orders.push(el);
  return acc;
}, {});
grouped = Object.values(grouped).sort((a,b) => a.dayNumber - b.dayNumber);

console.log(grouped)

The sorting of the orders array within each group is an aspect that may need further clarification from the original poster. To implement this, one would iterate through the result and perform the sort operation based on a specific property:

grouped.forEach(group => group.orders.sort((a, b) => {
  /* Sort logic based on unmentioned property */
});

Answer №3

Give this code a try

const array = [{
  "Pnl": 29.0035635,
  "date": "11/14/2022",
  "dayNumber": 1,
  "translationDayOfWeek": "Monday"
},
{
  "Pnl": 50.8878545,
  "date": "11/08/2022",
  "dayNumber": 2,
  "translationDayOfWeek": "Tuesday"
},
{
  "Pnl": 73.1014552,
  "date": "11/08/2022",
  "dayNumber": 2,
  "translationDayOfWeek": "Tuesday"
},
{
  "Pnl": 32.477,
  "date": "11/08/2022",
  "dayNumber": 6,
  "translationDayOfWeek": "Saturday"
},
{
  "Pnl": 25.43999561,
  "date": "09/30/2022",
  "dayNumber": 5,
  "translationDayOfWeek": "Friday"
},
{
  "Pnl": 17.6294068,
  "date": "09/30/2022",
  "dayNumber": 1,
  "translationDayOfWeek": "Monday"
}];
const newArray = [];

array.forEach((item) => {
    if (newArray.find(element => element.dayNumber === item.dayNumber)){
        const ind = newArray.findIndex(element => element.dayNumber === item.dayNumber)
        newArray[ind].info.push(item);
    }
    else {
        newArray.push({
            dayNumber: item.dayNumber,
            info: [item]
        })
    }
})

newArray.sort((x, y) => parseInt(x.dayNumber) - parseInt(y.dayNumber))

console.log(newArray)

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

The custom validation in Node.js using Express-Validator is ineffective

I have implemented custom validators using express-validator to include specific validations: middlewares.js module.exports = function (app) { console.log('making sure I am being called'); return function (request, response, next) { ...

Enhancing the Calculator Functionality in a React Program

I'm struggling to incorporate a reset button into the input field, similar to CE on a calculator. I'm facing challenges when it comes to integrating it within the existing code structure. import { useRef } from "react"; import './A ...

PHP can display content directly in the browser, without the need for jQuery

As I develop a web interface for an application that has longer processing times, a loading page is displayed to the user when it starts. An AJAX call then loads the output onto the page. Strangely, while browsing the PHP function directly in the browser r ...

What is the best way to ensure NPM package manager points to my custom version of a library?

Looking to address a bug in an NPM library. Seeking guidance on configuring my software to point to my customized version of the library using package.json instead of the generic version from npmjs.org. This way, I can effectively debug my own iteration o ...

When I click, I expect to retrieve the tr element, but instead, I am receiving the td element

When I have a table and click on a tr element, the function returns a td element instead. Can someone explain why this is happening? let func = function () { $("tr").on("click", (event) => { event.preventDefault(); event.stopPropaga ...

Develop a series of characters from an array of structures in the C programming language

As I venture into learning C programming, one of my current challenges involves converting a structure array into a string. My goal is to store various data points in the program efficiently. To do this, I've already set up a structure array and now n ...

How can I refresh the information without appending it to the existing table using JavaScript and jQuery?

I am currently utilizing the pusher API and I am facing an issue where the data gets added to my table every time a new state is called. Instead, I want to update the existing data in the table without creating a new row every time. I only want to add a ne ...

The declaration of a 2D array within the Class is not being properly initialized

In the Circle class, I am trying to create an array of points on the perimeter that are 10 degrees apart. class Circle: def __init__(self, rad, originX, originY): self.rad = rad self.woriginX = originX self.woriginY = originY ...

Why doesn't the 'Range' input type slide on React.js documentation, but it does on CodePen?

Can someone help me figure out why my range slider is not working in my React app? I copied the code from Codepen where it works fine, but in my app, it's not functioning properly. The slider doesn't slide when dragged and clicking on it doesn&a ...

Using Numpy to generate an array containing elements within a specified range of a particular element in a separate array

this is the issue I am facing: Provided: array A is structured as 12000,3 and array B is structured as 150. The first column of array A consists of time values, and B also consists of time values, but they are sampled at different rates, so they do no ...

When it comes to HTML5 drag and drop functionality, only the dragstart event is triggered

I have successfully implemented HTML5 drag&drop using jQuery UI, but now I want to switch to using pure HTML5 API. Currently, only the dragstart event is firing for me. I am not able to catch the rest of the events. However, everything seems to be fun ...

Is there a way to eliminate preflight requests from the $http header?

//loop through individual logins $rootScope.setting.instances.forEach(function(ins) { var header = { "Accept": "application/json", "Authorization": "Basic " + btoa( ins.uname + ':' ...

Loading content beforehand vs. loading it on the fly

I am facing a dilemma with loading a large amount of content within a hidden <div>. This content will only be revealed to the user upon clicking a button. Should I load this content beforehand or wait until it is requested? ...

Transforming a React, Redux, and MUI Menu into an Electron Application

I'm in the process of transforming a web-based React + Redux + MUI application into an Electron app. The original app features a main AppBar with multiple dropdown menus, each containing menu items that interact with the app's Redux store. While ...

Is the alias name absolute or converted to AliasId when establishing a connection with Sequelize and Migrations?

In my Housing model, I have a sequelize association set up like this: Housing.belongsTo(models.User, {as : Owner}); When adding the column to the model and Migrations file with this association, will the table be named "Owner" exactly as the Alias, or "Ow ...

Converting a Google font for compatibility with ThreeJS: A beginner's guide

Is there a way to convert a downloaded Google font from TTF to JSON in order to use it with ThreeJS FontLoader / TextGeometry? import LatoFont from '../assets/fonts/lato-bold.json' const loader = new FontLoader(); const font = loader.parse(LatoF ...

I keep encountering the error message "SyntaxError: Cannot use import statement outside a module" even after including "type": "module" in the package.json file. How frustrating to still be faced with yet another error

Upon running the code snippet provided, an error message is displayed stating "SyntaxError: Cannot use import statement outside a module." Despite successfully installing node-fetch using npm install node-fetch What could be causing this issue? import fet ...

Unleashing the power of storytelling with React: A guide to creating dynamic story

weather.stories.ts export default { title: 'Widgets/Forecast', component: Weather, } const Template: Story<any> = (args) => <Weather {...args} />; export const Default = Template.bind({}); Default.args = { forecast: { ...

Monitor the completion status of all Ajax requests using only JavaScript

I am aware of the ajaxStop method in jQuery. $(document).ajaxStop(function() { //Do something }); If jQuery is not available, is there a way to achieve this with pure JavaScript instead? If so, could you please provide an example? Thanks ...

Python implementation of dynamic N-dimensional finite difference computation along a specific axis

I am working on a function that calculates the finite difference of a 1d np.array and I am looking to expand it to work with n-dimensional arrays. The current function looks like this: def fpp_fourth_order_term(U): """Calculates the second derivative ...