How do I group data based on multiple conditions in JavaScript?

I have the data structured as follows:

[
  {
    "Id": 1,
    "Title": "Title_1",
    "Positive": 5,
    "CreateTs": 1674231433428
  },
  {
    "Id": 2,
    "Title": "Title_1",
    "Positive": 8,
    "CreateTs": 1674288139000
  },
  {
    "Id": 3,
    "Title": "Title_2",
    "Positive": 5,
    "CreateTs": 1674633970000
  },
  
  {
    "Id": 4,
    "Title": "Title_1",
    "Positive": 12,
    "CreateTs": 1674649613000
  },
  
  {
    "Id": 5,
    "Title": "Title_1",
    "Positive": 10,
    "CreateTs": 1674649741000
  }
  ]

Desired result:

  [
    // group by Title, and CreateTs in current week
    // Sum up the grouped number of Positive
    {
      "Title": "Title_1",
      "Positive_sum": 22
    },
    
    {
      "Title": "Title_2",
      "Positive_sum": 5
    }
  ]

Although I found a similar question, I couldn't fully comprehend it due to its complexity...

I attempted to use the array.slice method to extract initial terms, but since the data order varies each time, this was not effective. After researching different methods online with no success, I'm seeking assistance here.

Answer №1

function findMonday(d) {
    d = new Date(d);
    let dayOfWeek = d.getDay(),
        difference = d.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6:1); // adjust when the day is Sunday
    return new Date(d.setDate(difference));
}


let dataResults = [{"Title": "Title_A", "Total": 0}, {"Title": "Title_B", "Total": 0}];
let currentTimestamp = Math.floor(new Date(findMonday(new Date())).getTime() / 1000);
data.forEach(obj => {
    if (obj.Title === dataResults[0].Title && obj.CreatedAt > currentTimestamp) {
        dataResults[0].Total += obj.PositiveCount;
    }
    if (obj.Title === dataResults[1].Title && obj.CreatedAt > currentTimestamp) {
        dataResults[1].Total += obj.PositiveCount;
    }
});

This code can validate the title of an object and determine if the timestamp exceeds Monday of the current week.

Answer №2

To start, we must filter to obtain the current week's start timestamp and end timestamp and then apply this filter to CreateTs.

Next, we can utilize the reduce method to group our objects using an object instead of an array for ease of use. Afterwards, we will convert the object into an array using values().

const now = new Date();
const currentWeekStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getUTCDay());
const currentWeekEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (6 - now.getUTCDay()));

const result = data
    .filter((item) => {
        const date = new Date(item.CreateTs);
        return date >= currentWeekStart && date <= currentWeekEnd;
    })
    .reduce((acc, item) => {
        const { Title, Positive } = item;
        if (!acc[Title]) {
            acc[Title] = { Title, Positive_sum: Positive };
        } else {
            acc[Title].Positive_sum += Positive;
        }
        return acc;
    }, {});

console.log(Object.values(result));

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

Stranger things happening when incorporating a generator function in React

Here's a simplified version of my component. It includes a generator function that cycles through values. const App = () => { const [state, setState] = useState("1") function* stateSwitch () { while (true){ yield "2" yield "3" ...

Exploring JavaScript-based navigation with Python and Selenium

Here is the URL of the page in question: link. I am trying to navigate pagination with the following HTML markup: <li class="btn-next"> <a href="javascript:ctrl.set_pageReload(2)">Next</a></li> I have written a ...

What could be causing my node server's REST endpoints to not function properly?

Here is a snippet of my index.js file: var http = require('http'); var express = require('express'); var path = require('path'); var bodyParser = require('body-parser') var app = express(); var currentVideo = &apos ...

Build a flexible Yup validation schema using JSON data

I am currently utilizing the power of Yup in conjunction with Formik within my react form setup. The fields within the form are dynamic, meaning their validations need to be dynamic as well. export const formData = [ { id: "name", label: "Full n ...

Attempted to display a Google Map within a lightbox, but encountered difficulties in getting it to

I've copied and pasted my code below. It may contain references to Google or Lightbox being undefined, but I'm unsure how to integrate them into the code provided. My goal is to display a Google map within a Lightbox popup, but so far I have been ...

Utilizing dropbox.js in combination with OAuth 1: A step-by-step guide

I'm in the process of revamping a website that already exists, and although I have the code from the previous version, I'm encountering challenges replicating certain functionalities in the new iteration. Here's the situation: The user is ...

Retrieve the file name (as well as other properties) when clicking on an image in dropzone.js

Is there a way in dropzone.js to retrieve the file name of an uploaded image when it is clicked? Check out this resource for more information: ...

Acquire a JSON response from a web address by utilizing JavaScript

If you navigate to , you will find a JSON file filled with information about your current geolocation. My goal is to save this JSON data into JavaScript variables, allowing me to manipulate and extract specific fields from the file. ...

Sending DOM values to React components as properties

Forgive me if this question seems basic, as I am still learning ReactJs. I have a react component that displays the user's sign-in status: <AccountStatus iconsize="medium" activate={[true,false,true]}/> Image 1 //or using <AccountStatus i ...

To address the issue of input values not persisting in a Selenium iframe element, I am implementing a custom JavaScript event to

Attempting to initiate a JavaScript 'change' event on an element within an iframe. The following is the code snippet I have been using: // accessing the iframe window var iframeDoc = document.getElementsByTagName("iframe")[0].contentWin ...

Generating a download link with an expiration feature in node.js or express for both frontend and backend operations

Hello everyone, I'm a beginner here and have recently started working with node.js and express.js. I am looking to implement a download link on my website that expires after a certain time, but I've been struggling with the code for about a week ...

Tips for ensuring the CSRF token functions properly on the browser when utilizing Django and React

Apologies in advance if this question seems beginner-friendly, but I have developed an application with Django backend and React frontend. I am currently working on implementing the CSRF token for the post request on the create endpoint using the code snip ...

The argument type 'string' does not match the parameter type 'keyof Chainable' in Cypress JavaScript

Trying to incorporate a unique custom command in Cypress (commands.js file) as follows: Cypress.Commands.add("login", (email, password) => { cy.intercept('POST', '**/auth').as('login'); cy.visit(& ...

Exploring the depths of an array in PHP/Symfony

I am facing an issue with my PHP code: for($number=0; $number<=9;$number++) { switch($twigparams["entries"][$number]["continent"]) { case "Europe" : $europeanusers+=1; break; case "Asia" : $asiat ...

The overlay div is not displaying over my main div as intended

Having trouble with my overlay design - I've set up a button that should display an overlay div on top of my main div when clicked, but for some reason it's not appearing. Despite watching tutorials and looking for similar issues, I'm unable ...

How to delete the last item of an array in AngularJS using scope

In my Angular controller, I have an array and a method for deleting objects. function($scope, $http){ $scope.arrayOfObjects = []; $scope.remove = function(obj){ var i = $scope.arrayOfObjects.indexOf(obj); if( i > -1 ){ ...

Hiding the filelist on antd-Upload when the URL is not provided

When passing a Url as a prop to display uploaded files in an edit Modal, I want to ensure that no attachments are shown if the Url is empty. Currently, I am still seeing empty attachments displayed as shown in the image: https://i.sstatic.net/dkzu1.png ex ...

What is causing the result of this code to be 111111?

I'm struggling with this code snippet. I can't quite grasp how the output ends up being 111111. Any insights? public class Test { public static void main(String[] args) { int list[] = {1, 2, 3, 4, 5, 6}; for (int i = 1; i ...

The error callback in Jquery ajax is triggered despite receiving a 200 status code in the response

I am facing an issue with my ajax code. The success callback contains an alert that is not working properly. Here is the code snippet: $(".change_forex_transaction_status").click(function(){ $("#insufficient_funds").css("display","none"); var id = $( ...

Guide to converting a D3js Bar Chart race into an MP4 or video file

https://i.sstatic.net/5Ri0T.jpg let competition = d3.interval(function() {}, tickDuration); ...