"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

Display a JSON object on a web browser

I am trying to display a JSON object on a web browser using HTML. The object is already in a text file and has been properly formatted for readability. My goal is to maintain the same formatting when displaying it on the browser. ...

The ASIHTTPFormDataRequest encountered an issue while trying to create the request. It seems like there might be an error with the

I am facing an issue while trying to make a service call using ASIHTTPRequest with a POST method. Upon execution of the request, I encounter the following error: errorError Domain=ASIHTTPRequestErrorDomain Code=5 "Unable to create request (bad url?)" User ...

Add a new row to the table when a dropdown option is selected, and remove the row when deleted. Ensure that the row is only added

Here is my specific requirement: I need a table with a default row containing a dropdown menu in the first column. When an option is selected from the dropdown, a new table row should be added with the same content as the main row and a delete button for ...

"Enhance your website with the powerful combination of SweetAlert

I'm having trouble getting my ajax delete function to work with SweetAlert. I can't seem to find the error in my code. Can someone help me figure out how to fix it? function deletei(){ swal({ title: 'Are you sure?', ...

Utilizing NodeJS code and the SlackAPI to build a custom chatbot named PFBot

Recently, I came up with an idea for a Slack Bot that could censor inappropriate language used by users. For example, if a user types a curse word, the bot would automatically replace it with symbols based on the length of the word. Although I'm rela ...

Utilize the client-side JavaScript file with ejs framework

Recently, I have been working on creating a website using Express and EJS. I discovered that using just one JavaScript file for all my EJS (view) files was causing issues. If I target a DOM element in one view page and it doesn't exist in another, I w ...

Steps to dynamically adjust an element's width in CSS depending on the presence of a separate element

I have a text input box appearing on the left side with a button positioned next to it on the right. For certain pages, I want to display a checkbox next to the input box and move the button below it. Is there a way to achieve this using CSS flexbox or a ...

Mastering the art of managing promises within nested loops

Embarking on my Promise journey, I find myself faced with a scenario where a list of objects within another list of objects needs to be updated based on responses from an external API. I've attempted to simulate the scenario below. The code snippet f ...

What is the best way to cancel Interval in a React application?

I need help with implementing setInterval in my react redux application. Below is the code snippet from FileAction.js export const SetPath = ({ path, location }) => async (dispatch) => { try { let interval; if (pre_path === path) ...

What is the best way to merge 60 related jquery functions into a unified function?

I designed a webpage that serves as an extensive checklist. When you click on the edit button for a checklist item, a modal window opens up. This modal window contains a radio button to indicate whether any issues were found during the check. If "Yes" is s ...

What could be causing the issue with the .toLocaleTimeString method not properly converting time zones?

I have been attempting to convert timezones based on the current time, but I haven't had success. I tried switching from using date.toLocaleTimeString to date.toLocaleString, but it didn't work. I also tried changing the timezone from America/Den ...

effectively showcasing information in a datatable by converting JSON data into objects

I am looking for a way to display balance information in datatables, but I have not been able to find a solution yet. <!DOCTYPE html> <html lang="en"> <head> <title>Comment</title> <meta charset="u ...

Can you explain the distinction between the "DOMContent event" and the "load event"?

Within Chrome's Developer tool, there is a blue vertical line marked "DOMContent event fired", as well as a red line labeled "load event fired". Is it safe to assume that the "DOMContent event fired" signifies the initiation of inline JavaScript execu ...

How to display 3 items per row in a React table by utilizing a map function loop

Currently, my table using material UI generates one column on each row. However, I would like to display 3 columns as items on each row. Below is the mapping for my table: <TableBody> {this.props.data.slice(page * rowsPerPage, page * rowsPerPage ...

Unreliable Response from JEditable

I have encountered an unusual behavior while using the JEditable jQuery plugin to update data on my webpage. One specific field is not updating as expected, instead displaying the following message: EM29UPDATE NetLog SET grid = 'EM29&apo ...

What are the steps to integrate the vue-tweet-embed node package into vuejs2?

I am having trouble figuring out how to implement the vue-tweet-embed plugin in my Vue file. I keep getting an error message that says: Unknown custom element: - have you properly registered the component? If dealing with recursive components, ensure ...

Integrate Tailwind CSS into the bundled JavaScript file

Is there a way to integrate tailwind css into bundle js effectively? Take a look at this example involving vue 3 and tailwind 3 https://github.com/musashiM82/vue-webpack. Upon executing npm run build , it generates 3 files: app.js ABOUTPAGE.js app.6cba1 ...

What is the best way to empty the input field after a download event is completed in Node.JS?

For hours on end, I've been struggling with a persistent issue in my video downloader app. After successfully downloading a video, the input field where the URL is entered remains filled instead of clearing out. The screenshot below illustrates the p ...

What level of trust can be placed in MUI Global Class names when using JSS?

Here is my current code snippet: const formControlStyles = { root: { '&:hover .MuiFormLabel-root': { } } } Would it be considered secure to utilize the class name in theme overrides for connecting with other components? Furthe ...

React Big Calendar encountered an error: The element type provided is not valid, as it is expected to be a string for built-in

Error One: The element type is invalid: it was expecting a string (for built-in components) or a class/function (for composite components), but received undefined. This could be due to not exporting your component correctly from the file where it's d ...