"Utilize JavaScript to structure JSON, eliminate redundant entries, and calculate the total number

I'm feeling a bit disoriented, as I have this dataset in json format with timestamps and ids arranged like so:

[{
  "date":"2016-11-18 19:20:42","id_pa":"7"
},{
  "date":"2016-11-18 19:04:55","id_pa":"5"
},{
  "date":"2016-11-19 20:53:42","id_pa":"7"
},{
  "date":"2016-11-19 20:53:43","id_pa":"7"
},{
  "date":"2016-11-19 20:53:43","id_pa":"7"
},{
  "date":"2016-11-20 20:49:42","id_pa":"7"
},{
  "date":"2016-11-20 20:50:45","id_pa":"7"
},{
  "date":"2016-11-20 20:50:46","id_pa":"7"
}]

My goal is to create a new json that shows the date along with the total count of IDs for each day. The resulting Json structure should look something like this:

[{
  "date":"18-11-2016","num_pa":"2"
},{
  "date":"19-11-2016","num_pa":"1"
},{
  "date":"20-11-2016","num_pa":"1"
}]

I believe I need to utilize a .map function to format the date into dd-mm-yyyy, followed by a .filter to eliminate duplicates, and finally a .reduce to tally up the different ids for each date. So far, I've managed to complete only the .map procedure but I'm uncertain of the next steps, as well as whether my solution is optimal or not.

This snippet represents part of my code:

SwapSvc
    .getUsage (vm.id_fi)
    .then((data)=>{
        //console.log(`lreceived data: `+ JSON.stringify(data) );
        vm.fdata = data.map((elem) => {
        //console.log(`date: ${elem.date}`);
        //console.log(`id_pa: ${elem.id_pa}`);
        var d = new Date (elem.date);
        return{
            date:d.getDate()+'-'+d.getMonth()+'-'+d.getFullYear()/*elem.date*/,
            id_pa:elem.id_pa
        }})
        var temp = [];
        vm.filteredData = vm.fdata.filter((elem, index) => {
            if(temp.indexOf(elem.date)<0){
                temp.push(elem);
                return true;
                }
            else return false;
        });
        console.log(`data after parsing and ordering: `+ JSON.stringify(vm.filteredData) ); 
        return data;
    })
    .catch((err)=>{
        //error
        console.log(`error, no response`);
        throw err;
    });

PS: My development environment comprises Angular 1.6 using ES6. Appreciate your help in advance BRJ

Answer №1

If you are looking to organize data by date and keep track of all unique `id_pa` values, a hash table can be quite useful.

var data = [{ date: "2016-11-18 19:20:42", id_pa: "7" }, { date: "2016-11-18 19:04:55", id_pa: "5" }, { date: "2016-11-19 20:53:42", id_pa: "7" }, { date: "2016-11-19 20:53:43", id_pa: "7" }, { date: "2016-11-19 20:53:43", id_pa: "7" }, { date: "2016-11-20 20:49:42", id_pa: "7" }, { date: "2016-11-20 20:50:45", id_pa: "7" }, { date: "2016-11-20 20:50:46", id_pa: "7" }],
    hash = Object.create(null),
    result;

data.forEach(function (item) {
    var dateKey = item.date.slice(0, 10);
    hash[dateKey] = hash[dateKey] || Object.create(null);
    hash[dateKey][item.id_pa] = true;
});
result = Object.keys(hash).map(date => ({ date, unique_ids: Object.keys(hash[date]).length }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To check if the object already exists within the array created by the reduce function, you can easily chain a reduce onto your map call and utilize the ES6 findIndex method.

DataService
    .fetchData (vm.id_fi)
    .then((data)=>{
        //console.log(`Received data: `+ JSON.stringify(data) );
        vm.fdata = data.map((elem) => {
            //console.log(`Date: ${elem.date}`);
            //console.log(`ID: ${elem.id_pa}`);
            var date = new Date (elem.date);
            return{
                date:date.getDate()+'-'+date.getMonth()+'-'+date.getFullYear(),
                id:elem.id_pa
            }}).reduce((previous, current, index) => {
                var existingIndex = previous.findIndex(x => x.date === current.date);
                if (existingIndex !== -1) previous[existingIndex].count++;
                else previous.push({"date": current.date, "count": 1})
                return previous;
            }, [])

        console.log(`Data after parsing and ordering: `+ JSON.stringify(vm.fData) ); 
        return 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

Inject the content loaded from the server into a div element, and insert that div at the

I am trying to insert the div(#loadmore) element inside the div(#boxchatting) element when the content from "result.php" is loaded into div(#boxchatting). Here is the code I used: $('#loadmore').prependTo('#boxchatting'); $('#boxc ...

Guide: Enhancing Query Context within jQuery Instances Spanning Across Iframes

In my current project, I am facing a challenge with using a jQuery instance across iframes. It's been causing me quite a bit of frustration. Here's the situation: I have an existing web application that loads jQuery (which is aliased as $jq) in ...

Issue with event listener arising once elements have been loaded into the dom

I have a project where I want to click on a category card to obtain its id and then redirect to the movies screen. I understand that using row.eventlistener() in index.js executes before the elements are rendered, causing the id not to be captured. How ca ...

Utilizing setState within the useEffect hook can lead to the application experiencing

Why does my code result in an endless loop error? This issue is pointing to the line marked with *: function Blog() { const [blog, setBlog] = useState({}); const query = useQuery(); async function fetchBlog(query) { const data = awai ...

Steps to refresh the templateCache in AngularJS

angular.module('genTemplates', []) .run(['$templateCache', function($templateCache) { $templateCache.put('admin-article.html', '<div>......</div>'); ...... }]) ...

Experiencing a 404 error with angular.js while working on a MEAN application with gulp

I'm facing an issue while setting up a new MEAN app using gulp and bower. Whenever I launch my app, I keep encountering 404 errors for my bower dependencies. I utilized express-generator to create the folder structure, but my intention was to leverage ...

A guide on extracting the values of checked checkboxes by their ID using javascript

I'm currently attempting to extract the values of selected checkboxes. These checkboxes have distinct IDs because they are specified within a modal window. <input type = 'checkbox' id = 'audience_Name-$row[asset_ID]' value = &a ...

Understanding the response from an AJAX call

VB code Dim temp3 As String = dt.ToString() cmd.Connection = con con.Open() i = cmd.ExecuteNonQuery() con.Close() If i = 1 Then msg = "Record successfully inserted" ...

Lighthouse Issue: Facing PWA Challenges with a "Request Blocked by DevTools" Error

For hours now, I've been struggling to make Lighthouse work in Chrome for my initial PWA project. I feel completely lost as nothing seems to be making sense despite the basic code I have included below. The issue arises when I load the page normally ...

How do I retrieve and display all the locally stored variables in Angular 2/JavaScript and calculate the total number of keys present in the localStorage?

Currently, I'm developing a project in Angular2 that involves the storage of user-added items to a shopping cart. To accomplish this, I have opted to utilize local storage to temporarily save the items. Each category (such as shoes, clothes, etc.) is ...

AngularJS - Retaining the initial value without submitting

On the left side, I have a list of users with corresponding details displayed on the right. The form handles the details on the right using inputs with ng-model. Whenever I click on a user from the left section, the selected user changes and the model auto ...

Navigating through a MongoDB (JSON) document using queries: A beginner's guide

My JSON document includes: { "_id" : ObjectId("5b6049f845d12b6b62bf6fca"), "original_query" : "", } I aim to iterate through each individual in the 'like' field and then store their fb_id in a python list. Being new to mnogodb, JSON, I am seek ...

Tips for displaying multiple results from a MySQL query in a single .ejs file using Node.js and Express

Currently diving into Node.js and working on a web application, I am faced with the challenge of rendering twice in the same .ejs file. Consider the scenario presented in the following .ejs file: <table> <% rows.forEach(function(ind){ %> /* m ...

Tips for Retrieving Data from a Multi-Dimensional Array

I need help accessing the values in my array and assigning them to variables for later use. I have created an array and used the randomGo() function to generate a random number that corresponds to a pair of numbers within the array. My goal is to assign ...

Creating an interactive quiz using JSON and distributing the results from a SQL query into a multidimensional array

Working on a quiz system that stores questions and answers in a MySQL database has led me to try and convert the data into a multidimensional array and then into JSON format. However, the result is not meeting my expectations and I'm stuck with the cu ...

Is there a way to divide or segment excessive JSON Files using AWS glueContext prior to their conversion to JSON format?

I am currently working on converting a large 20GB JSON gzip file to parquet format using AWS Glue. I have set up a job using Pyspark and included the code below. During this process, I encountered the following WARN message: LOG.WARN: Loading one large ...

AngularJS $location Redirect Error: Property 'path' Undefined

I'm struggling with an issue in my AngularJS code where I am trying to change the URL without reloading the page when a submit button is clicked. However, I keep getting a TypeError: Cannot read property 'path' of undefined in the console. ...

Binding hover and load events using jQuery on elements that are dynamically generated

One should note that the click event can be successfully bound to an element with the class name keybox, even if this element is dynamically generated. The code for this would look like: $('body').on('click', '.keybox', funct ...

Error in THREE.js: The function material.onBeforeRender is not defined

Can someone assist me with an error I'm encountering while trying to run my code in Three.js? The error message reads as follows: three.js:19528 Uncaught TypeError: material.onBeforeRender is not a function at renderObject (three.js:19528) at ...

Invoke PHP by clicking on a button

I am facing an issue with a button I have created. Here is the code for it: <input type="submit" name="kudos_button" value="★ Give kudos"/>' To test it, I wrote a PHP script like this below the </html> tag: ...