What is the best way to sort and organize this JSON data?

There is an array of JSON objects named events that contains fields such as eventId, eventName, and the date of the event.

[{event1}, {event2}, {event3}];

The goal is to iterate through this array and filter out events that occur on the same day. The desired output should look like this:

"days": [
    {
        "date": "11-05-2015",
        "events": [
            {"eventId": 1, ...},
            {"eventId": 2, ...},
            {"eventId": 3, ...},
            {"eventId": 4, ...},
        ]
    },

What is the most efficient way to achieve this using JavaScript or Angular?

Answer №1

To organize the events by date, create a new object where the dates are keys and the corresponding events are stored in arrays. Once you have mapped the dates to events, convert the map into an array with your preferred structure.

If the original data is stored in a variable named "events":

    var events  = [{event 1}, {event 2}...];
    var daysMap = {};
    var days = [];
    events.map(function(event) {
        if (days[event.dateofevent] === undefined) {
            days[event.dateofevent] = [];
        }
        days[event.dateofevent].push(event);
    });
    for (var day in daysMap) {
        days.push({
            date: day, 
            events: daysMap[day]
        });
    }

Answer №2

Creating a dynamic shopping cart with AngularJS

<div ng-app>
    <span class="bold">Showing how to filter and sort items using Angular JS</span>
    <br /><br />
        <div ng-controller="ShoppingCartCtrl">        
            <div>Sort by: 
            <select ng-model="sortExpression">
                    <option value="Name">Name</option>
                    <option value="Price">Price</option>
                    <option value="Quantity">Quantity</option>
                </select>
            </div>
            <br />
            <div><strong>Filter Results</strong></div>
            <table>
                <tr>
                    <td>By Any: </td>
                    <td><input type="text" ng-model="search.$" /></td>
                </tr>
                <tr>
                    <td>By Name: </td>
                    <td><input type="text" ng-model="search.Name" /></td>
                </tr>
                <tr>
                    <td>By Price: </td>
                    <td><input type="text" ng-model="search.Price" /></td>
                </tr>
                <tr>
                    <td>By Quantity: </td>
                    <td><input type="text" ng-model="search.Quantity" /></td>
                </tr>
            </table>
            <br />
            <table border="1">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Price</th>
                        <th>Quantity</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="item in items | orderBy:mySortFunction | filter:search">
                        <td>{{item.Name}}</td>
                        <td>{{item.Price | currency}}</td>
                        <td>{{item.Quantity}}</td>
                    </tr>
                </tbody>
            </table>
            <br />
</div>
</div>

Defining the AngularJS controller function

function ShoppingCartCtrl($scope)  {

        $scope.items = [
            {Name: "Soap", Price: "25", Quantity: "10"},
            {Name: "Shaving cream", Price: "50", Quantity: "15"},
            {Name: "Shampoo", Price: "100", Quantity: "5"}
        ];

        $scope.mySortFunction = function(item) {
            if(isNaN(item[$scope.sortExpression]))
                return item[$scope.sortExpression];
            return parseInt(item[$scope.sortExpression]);
        }
}

Styling the elements with CSS

.bold { font-weight:bold; }

table td{
    padding: 10px;
}

table th{
    font-weight: bold;
    text-align: center;
}

Check out the demo here

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

Cordova Geolocation now displaying incorrect latitude and longitude values as NAN

Recently starting out with javascript and Cordova, I decided to develop a basic GPS app in Visual Studio 2015. The goal was simple: get my current position by clicking on the "CURRENT POSITION" button. Testing it in Firefox yielded positive results. Howev ...

Tips for creating a responsive Youtube embedded video

Check out this website for a good example: If you take a look, you'll notice that the header youtube video is responsive - it automatically resizes when the window size changes. Here are the <iframe> codes: <iframe id="bluetube-player-1" fr ...

In what way can you dynamically set the displayName using a higher order component?

My current struggle is setting displayName dynamically in order to improve the debugging process. Each component renders as <Component ... />, making it difficult to identify them in the codebase. While I have successfully set static displayName on e ...

Tips for sending event and additional arguments to a click handler

Hi there, I recently created a canvas using easelJS. Within my canvas, I have points that have a click handler defined for them with this syntax: p.on("click", handleMouseClickEvent); However, I am facing an issue when trying to pass arguments to the han ...

Utilize Angular to transform items in a nested array into comma-delimited values prior to assigning them to a grid

Here is an excerpt from a JSON response retrieved from an API: { "totalCount": 2, "customAttributes": [ { "objectType": "OWNER", "atrributeId" ...

Is the purpose of express.json() to identify the Request Object as a JSON Object?

app.js const express = require('express'); const cookieParser = require('cookie-parser'); const session = require('express-session'); const helloRouter = require('./routes/hello'); const app = express(); app.set(& ...

MySQL Workbench refuses to import JSON files, displaying error code 1290

I have a situation where my test suite generates a .json file that I need to store in MYSQL. It doesn't matter how it's stored, I just want to be able to access it when needed. After doing some research online, I attempted the typical approach v ...

My string is being cut off due to the HTML value

My webpage utilizes HTML5 to enable file uploads directly from the browser. The uploaded file is a PDF that needs to be displayed within an <input type="text"/> The following is my code snippet: var files = evt.target.files; // FileList object // ...

What steps do I need to take in order to implement a functional pagination menu in Vue?

I downloaded and installed laravel-vue-pagination with the following command: npm install laravel-vue-pagination After that, I globally registered it in my app.js file: Vue.component('pagination', require('laravel-vue-pagination')); F ...

Live streaming updates directly from Firebase

In order to achieve real-time updates from Firebase, my objective is to retrieve comments from Firebase and display them on this.note. I seem to have made a mistake in the update() function. Here is the tutorial I followed: link. methods: { update(){ db.c ...

Utilizing ng-repeat to loop through a div element that consists of various nested tags

I need to display multiple tabs, with each tab having a table where the values are populated from a database. The number of tabs is dynamic and fetched from another page of the application. All tables have the same structure but different values. How can I ...

Populate the JTable with SparQL query results in JSON string format

Trying to populate a jtable with json data, I experimented with various solutions such as: String json = " ObjectMapper mapper = new ObjectMapper(); List<User> users = mapper.readValue(json,TypeFactory.defaultInstance().constructCollectionType(List ...

I developed a straightforward MVC application that sends an HttpGet request and delivers an array containing 7 randomly generated, unidentified numbers to the View. [RESOLVED

A new MVC app was launched with a simple task of generating 7 random numbers between 0 and 9 to be placed at positions 1 through 7 (without starting with 0). Initially, the numbers are hidden with "X" marks. When the user clicks on the "Submit" button and ...

Arrange an array of objects based on boolean values first, followed by numerical values in JavaScript

I am facing a challenge where I have an array of objects that need to be sorted based on two rules, following a specific order: Firstly, objects with the "departeYet" property set to true should come first. Secondly, the objects must then be sorted numeri ...

Monitoring a specific property within an array of objects with AngularJS

I am facing an issue with the data in my controller $scope.data = { home: { baseValue: "1", name: "home" }, contact: { baseValue: "2", name: "contract" } // numerous ...

What could be causing redux.props.reducer to return undefined?

I recently encountered an issue with my code. I have a function in the actions folder that successfully fetches a URL using axios. However, there seems to be a problem when trying to retrieve the data from the reducer. I have a mapStateToProps function set ...

Unusual actions exhibited by the fs.readdirSync function

My environment consists of nodejs 5.5.0 and pm2 1.0.1. I execute the script using: npm start The script is defined in package.json as: "scripts": { "start": "pm2 start bin/www --watch" }, I have a basic script that retrieves a list of videos and it ...

Ways to retrieve the final appearance of element m in array n

As a beginner in programming, my goal is to access the last position of element m within array n. The following code displays all positions of element m: var n = []; while (true) { let input = prompt("Please enter a number for the ...

Substitutions not functional when using SendGrid in conjunction with Firebase functions

I'm encountering difficulties when trying to include substitutions data in emails sent from Sendgrid using Firebase Cloud Functions. Here's my function exports.firestoreEmail = functions.firestore .document('users/{id}') .onCreate(s ...

Tips for creating emissiveMap lighting exclusively in dimly lit spaces using three.js

Using three.js, I am able to render the earth with textures and add an emissive texture for city lights. However, I am facing a problem where even the light areas of the earth emit city lights. For example: https://i.sstatic.net/hZ1Cr.png Is there a way ...