How to make an element with specific class ignore a global listener? [duplicate]

There is a global listener on specific input type:

$('input[type["radio"]').on('change', function() { ... });

But I have another more specific radio input with its own unique_radio class:

<input type="radio" class="unique_radio" name="unique_radio">

It also has its own click listener:

$('.unique_radio').on('click', function() { ... });

When I click it, both listeners trigger the functions, but I need only the function with the unique_radio listener to be triggered.

I have tried using stopImmediatePropagation and off as seen here:

Best way to remove an event handler in jQuery?

But that did not seem to work

upload form-data with no file(image) in react native

I am trying to call a form-data content type API, where image is optional. That is working in postman as shown in below picture.enter image description here

I am trying like below way

        let body = new FormData()

        if (imageData != null) {
            body.append('image', {
                uri: imageData.uri,
                name: imageData.fileName,
                type: imageData.type
            })
        } else {
            body.append('image', new Blob([]))


            // body.append('image', null)  -> tried

            // body.append('image', "")  -> tried

            // -> tried
            // body.append('image', {
            //     uri: "",
            //     name: "",
            //     type: ""
            // })

            // -> tried
            // body.append('image', {
            //     uri: ""
            // })
        }

How can i call API just like that is showed in the postman image. Without selecting an Image.

Assign tags above 9 to message in Thunderbird

Are there any commands or functions in Thunderbird that assigns a specific tag to a message? I have more than nine tags, so I need more shortcuts.

I have installed the tbkeys add-on: https://github.com/wshanks/tbkeys
I’m able to assign commands and functions like func:AddTag and cmd:cmd_addTag, but those adds a brand new tag. I would like to use one of the tags I’ve already defined.

I would think that assigning a tag to a message is something needed much more often than adding a new tag, so it’s strange that I can’t find a way of doing it. I looked through the list here: https://hg.mozilla.org/comm-central/file/tip/mail/base/content/mainCommandSet.inc.xhtml
But the mailTagMenuItems only has addTag, mangeTags and removeTags.

Are there nothing like AssignTag(‘NameOfTag’)?

Expo Go crashes when using captureRef without logging anything

I have a View containing an image with another view overlaying it. I wish to use captureRef to save the image with the overlay, but when ever I try this Expo Go crashes without leaving any logs or error messages. Is there anything that could be causing this?

//I have a button that calls this. This is what crashes the app
const savePicture = async () => {
    const result = await captureRef(savedPicture, {
        result: 'tmpfile',
    })
}

// if photoData isn't undefined we render this
<View style={styles.container} ref={savedPicture}>
    <Image source={{ uri: photoData.uri }} style={styles.camera}/>
    <View style={styles.overlay}>
        <View style={styles.shape}/>
    </View>
</View>

What I’m trying to do is similar to this https://kyleclutter.medium.com/react-native-adding-overlay-date-stamp-to-photo-7c7299327004

Docs for captureRef: https://docs.expo.dev/versions/latest/sdk/captureRef/

Show only 3 number of pages in custom pagination React js

I have implemented custom pagination in React js which is working perfect. The issue is the I am getting all page no I want to limit that to just 3 at a time

  <div className={['paginationContainer', `${totalNoOfElements >= postPerPage ? "" : "hideDisplay"}`].join(' ')}>
            <span onClick={() => { backPage() }}>
                <IoIosArrowBack className={['arrow', `${currentPage > 0 ? "" : "disableCursor"}`].join(' ')} />
            </span>
            {(() => {
                let numberOfPages = [];
                for (let i = 0; i < totalNoOfPages; i++) {
                        numberOfPages.push(
                            <a key={i}
                                className={["numberPag", `${currentPage === i ? "activePagBtn" : ""}`].join(' ')}
                                onClick={() => handlePageClick(i)}>
                                {i + 1}
                            </a>
                        );
                    }
                    return numberOfPages
            })()}
            <span onClick={() => nextPage()}>
                <IoIosArrowForward className={['arrow', `${currentPage + 1 < totalNoOfPages ? "" : "disableCursor"}`].join(' ')} />
            </span>
        </div>

My page number are being generated in the tag. How can I limit to just 3 at a time and when i click next arrow icon, then it shows the remaining extra pages

How I can use one js code of a django template for different content

I am working on a web application using Django I have faced one problem in that and that’s I wrote one html template in Django and in that template I also has been written the code of js for that template. I want to use that js code for all the different kinds of content that is represented using that template in the front of the user.but that js code is not working for all kinds of content similarly.

Problem in brief

I am making a commerical web application for a Project like amazon.in and flipkart.com and I have writen a template for a product view page for all kinds of Product that is shown using that template. I has been made a button in that product view page template. Button is Add to Cart and I have written JavaScript code in that template for add to Cart button to store the product in the cart when the user click the button. I made my cart using LocalStorage and i will store the products in it.
but the problem is when I initialzed my site and click on the product and goes to the product view page and click to the Add to Cart and after click on it the js code will be executed successfully!! and the product will be stored in localStorage of the browser. but When I goes back to the Products list page and click on the another Product and goes to its Product view page and then I click the Add to Cart Button it will do nothing and show some kind of error which is about Uncaught Type Error and the product is not listed in the cart. but when I clear my cart (localStorage) by using localStorage.clear() and when it is empty the product is listed in the localStorage after clicking on the Add to Cart Button.
and when one Product is listed in it. it show same error again for other one. so How I can solve it and gets my desired result.

if you know that how it will be solved so please share with and help me out and please let know also what kind of mistake i am doing in that.

My product view template code is here with js code embaded

{% extends 'MenuCategory/Navigation_bar.html' %}
{% block title %} {{Category.Item_Category}} {% endblock %}
{% block style %}
{% endblock %}
{% block head %}
{% endblock %}
{% block body %}
<div class="container-fluid mt-3">
    <div class="list-group">
        {% for item in Content %}
        <a href="#" class="list-group-item list-group-item-action" aria-current="true">
            <div class="row">
                <div class="col-1 d-flex align-items-center">
                    <img src="/media/{{item.Item_Image}}" class="rounded img-fluid" width="150px" height="150px">
                </div>
                <div class="col-8">
                    <div class="d-flex w-100 row">
                        <h5 id="nameby{{Category.Item_Category}}Product{{item.Item_ID}}" class="mb-1">{{item.Item_Name}}</h5>
                        <div class="d-flex w-100 row">
                            <p class="mb-1">{{item.Item_Description}}</p>
                        </div>
                        <div class="d-flex w-100 row">
                            <small id="PriceOf{{Category.Item_Category}}Product{{item.Item_ID}}">{{item.Item_Price}}</small>
                        </div>
                    </div>
                </div>
                <div class=" col-3 d-flex justify-content-end align-items-center mr-2">
                    <span id="btnspan{{Category.Item_Category}}Product{{item.Item_ID}}" class="AddBtn">
                        <button id="{{Category.Item_Category}}Product{{item.Item_ID}}" class="btn btn-primary {{Category.Item_Category}}CartButton">Add to Cart</button>
                    </span>
                </div>
            </div>
        </a>
        {% endfor %}
    </div>
</div>
{% endblock %}
{% block script %}

document.getElementById("NavbarMainHeading").innerHTML="{{Category.Item_Category}}";
function updateCart(Cart) {
    for (let item in Cart) {
        console.log(item)
        document.getElementById('btnspan' + item).innerHTML = `<button id="minus${item}" class="btn btn-primary minus">-</button><span id="val${item}">${Cart[item][0]}</span><button id="plus${item}" class="btn btn-primary plus">+</button>`
    }
    localStorage.setItem('Cart', JSON.stringify(Cart))
    console.log(localStorage.getItem('Cart'))
}


if (localStorage.getItem('Cart') == null) {
    var Cart = {};
} else {
    Cart = JSON.parse(localStorage.getItem('Cart'))
    updateCart(Cart)
}

let btns = document.getElementsByClassName('{{Category.Item_Category}}CartButton');
btns = Array.from(btns);
for (let i = 0; i < btns.length; i++) {
    btns[i].addEventListener('click', function() {
        var idstr = this.id.toString();
        if (Cart[idstr] != undefined) {
            Cart[idstr][0] = Cart[idstr][0] + 1;

        } else {
            name = document.getElementById("nameby" + idstr).innerHTML;
            price = document.getElementById("PriceOf" + idstr).innerHTML;
            quantity = 1;
            Cart[idstr] = [quantity, name, parseInt(price)];
        }
        updateCart(Cart)
    })
}

{% endblock %}

My urls.py code is here

from django.urls import path,include
from . import views
urlpatterns = [
    # path('admin/', admin.site.urls),
    path('',views.CategoryPage,name='MenuCategoryPage'),
    path('Category/<str:Variety_Name>',views.Category_Items,name='CategoryItems')

My views.py of Django code is here

from django.shortcuts import render
from django.http import HttpResponse
from .models import Varieties,CategoryItems
def Category_Items(request,Variety_Name):
    print(f"variety name {Variety_Name}")
    post=CategoryItems.objects.filter(Item_Category=Variety_Name)
    Category=None
    print(len(post))
    if len(post) >= 1:
        Category=post[0]
    content={'Content':post,'Category':Category}


    return render(request,'MenuCategory/Product_List.html',content)

My models.py code is here

from django.db import models

# Create your models here.
class Varieties(models.Model):
    VarietyID=models.AutoField(primary_key=True)
    Variety_Name=models.CharField(max_length=50,default='Variety name should be within 50 characters.')
    Variety_Image=models.ImageField(default='')

    def __str__(self):
        return self.Variety_Name
class CategoryItems(models.Model):
    Item_ID=models.AutoField(primary_key=True)
    Item_Category=models.CharField(max_length=50,default="Variety Name and Category Name must be same.")
    Item_SubCategory=models.CharField(max_length=50,default="SubCategory Name")
    Item_Image=models.ImageField(default='')
    Item_Name=models.CharField(max_length=50,default='Ex: Paneer Pratha')
    Item_Price=models.IntegerField()
    Item_Description=models.CharField(max_length=1000,default='Write Something about speciality of the Product.')
    def __str__(self):
        return f"{self.Item_Name} - {self.Item_Category}"

Error that occur in Console when I want to add an item in the cart when localStorage already have one item in it
When I want to add an item from a different category after adding one item in the cart its showing this kind of error and item is not stored in the localStorage

But When localStorage is Empty the item is Stored in it Successfully
When localStorage is Empty it Added Items from the same Page but when the category and the item is changed it shows error and can't add an item in the cart.

problem in fetching data from api while using react kanban package

while fetching data locally it works but while fetching data from the api it doesnot displays . `

       <Board
            initialBoard={content}
            renderColumnHeader={({ name, badge }) => (
              <RenderCardTitle name={name} badge={badge} />
            )}
            renderCard={(data, { dragging }) => (
              <CardTaskBox data={data} dragging={dragging} content={content}  >
                {data}
              </CardTaskBox>
            )}
            onNewCardConfirm={draftCard => ({
              id: new Date().getTime(),
              ...draftCard,
            })}
            onCardDragEnd = {onCardMove}
          />

`
tried many times but i am not getting the point why this issue is arising??

this completely works when passing local data but not works white passing the data coming from api

How to prevent the div(s) in Requisite box from dragging into Pre-requisite box?

I’m working on a project where the user can drag and drop courses from “Required courses for track” list to “Required Courses” and vice-versa.
The same works with “Pre-requisite courses” and “Pre-requisite courses for track”

But those courses are also dragging into each other and creating a functionality that I do not want, how can I prevent the required courses from dragging into the pre-requisite section and the Pre-requisite courses to Requisite section?

I tried creating different Dividers for hosting

  1. Required courses and required courses for track
    and
  2. Pre-requisite courses and Pre-requisite courses for track
    but that doesn’t seem to work

HTML:
`

    <div>
    <!--First Drop Target-->
<div data-drop-target="true">
  <h4>Required courses</h4>
          <div id="box1" draggable="true" class="white">Course1</div>
          <div id="box2" draggable="true" class="white">Course2</div>
 
          
    </div>

    <!--Second Drop Target-->
    <div data-drop-target="true">
    <h4>Required courses for track</h4>
       <div id="box3" draggable="true" class="white">Course3</div>
          <div id="box4" draggable="true" class="white">Course4</div>
  <div id="box5" draggable="true" class="white">Course5</div>
    
    </div>
</div>

    <div>
    <!--First Drop Target-->
<div data-drop-target="true">
  <h4>Required courses</h4>
          <div id="box6" draggable="true" class="white">Course1</div>
          <div id="box7" draggable="true" class="white">Course2</div>
 
          
    </div>

    <!--Second Drop Target-->
    <div data-drop-target="true">
    <h4>Required courses for track</h4>
       <div id="box8" draggable="true" class="white">Course3</div>
          <div id="box9" draggable="true" class="white">Course4</div>
  <div id="box10" draggable="true" class="white">Course5</div>
    
    </div>
</div>

`

CSS:
`


h4 {
  color: #e87500;
  margin-top: 0px;
}


[data-drop-target] {
            height: 200px;
            width: 500px;
            margin: 25px;
            background-color: lightgray;
            float: left;
        }
        .drag-enter {
            border: 2px dashed #000;
        }
        .box {
            width: 100px;
            height: 100px;
      float: left;
      
        }
    .box:nth-child(3) {
      clear: both;
    }
        .red {
            background-color: firebrick;
      border: 1px solid black;
    }
        .white {
            background-color: white;
      border: 1px solid black;
        }

`

JS:
`

//Function handleDragStart(), Its purpose is to store the id of the draggable element.
        function handleDragStart(e) {
            e.dataTransfer.setData("text", this.id); //note: using "this" is the same as using: e.target.
        }//end function


        //The dragenter event fires when dragging an object over the target. 
        //The css class "drag-enter" is append to the targets object.
        function handleDragEnterLeave(e) {
            if(e.type == "dragenter") {
                this.className = "drag-enter" 
            } else {
                this.className = "" //Note: "this" referces to the target element where the "dragenter" event is firing from.
            }
        }//end function



        //Function handles dragover event eg.. moving your source div over the target div element.
        //If drop event occurs, the function retrieves the draggable element’s id from the DataTransfer object.
        function handleOverDrop(e) {
            e.preventDefault(); 
      //Depending on the browser in use, not using the preventDefault() could cause any number of strange default behaviours to occur.
            if (e.type != "drop") {
                return; //Means function will exit if no "drop" event is fired.
            }
            //Stores dragged elements ID in var draggedId
            var draggedId = e.dataTransfer.getData("text");
            //Stores referrence to element being dragged in var draggedEl
            var draggedEl = document.getElementById(draggedId);

            //if the event "drop" is fired on the dragged elements original drop target e.i..  it's current parentNode, 
            //then set it's css class to ="" which will remove dotted lines around the drop target and exit the function.
            if (draggedEl.parentNode == this) {
                this.className = "";
                return; //note: when a return is reached a function exits.
            }
            //Otherwise if the event "drop" is fired from a different target element, detach the dragged element node from it's
            //current drop target (i.e current perantNode) and append it to the new target element. Also remove dotted css class. 
            draggedEl.parentNode.removeChild(draggedEl);
            this.appendChild(draggedEl); //Note: "this" references to the current target div that is firing the "drop" event.
            this.className = "";
        }//end Function



        //Retrieve two groups of elements, those that are draggable and those that are drop targets:
        var draggable = document.querySelectorAll('[draggable]')
        var targets = document.querySelectorAll('[data-drop-target]');
    //Note: using the document.querySelectorAll() will aquire every element that is using the attribute defind in the (..)


        //Register event listeners for the"dragstart" event on the draggable elements:
        for(var i = 0; i < draggable.length; i++) {
            draggable[i].addEventListener("dragstart", handleDragStart);
        }

        //Register event listeners for "dragover", "drop", "dragenter" & "dragleave" events on the drop target elements.
        for(var i = 0; i < targets.length; i++) {
            targets[i].addEventListener("dragover", handleOverDrop);
            targets[i].addEventListener("drop", handleOverDrop);
            targets[i].addEventListener("dragenter", handleDragEnterLeave);
            targets[i].addEventListener("dragleave", handleDragEnterLeave);
        }
        

`

Display data based on response code from server after loader is loader is completed inside JSX?

I’m using react and redux-toolkit to call the backend API. I have create initial state like

     const initialState = {
        sessionInfo: {},
        loading: false
     };

    export const validateSession = createAsyncThunk(
    'merchant/validate',
    async (params, {dispatch}) => {
       const data = {
            type : "",
            source : "",
        }
       const res = await SessionValidate.validateSession(data)
       if(res.status === 200) {
        return res.data
       }
    }
)

const sessionValidation = createSlice({
    name:"sessionValidation",
    initialState,
    extraReducers: {
        [validateSession.fulfilled]: (state, { payload }) => {
            state.sessionInfo = payload
            state.loading = false
        },
        [validateSession.pending]: (state, { paylaod }) => {
            state.loading = true
        },
        [validateSession.rejected]: (state, { paylaod }) => {
            state.loading = false
        }
    } 
})

Now, I fetch the store data from one of the react component to display the loader and data.

I already written working JSX code for my desired output.

NOW THE PROBLEM STATEMENT

Redux-tookit’s extrareducers have this lifecycle of fulfilled, reject , pending. Now, on pending state the loader state becomes TRUE. That point the loader component needs to fireup inside JSX.
Later, request got fulfilled and response is saved inside sessionInfo object and loader becomes false.

Now my designed output should be.
Show loader on api startup and once api request is completed, remove loader from jsx and check the code inside response object and display content accordingly.

Everthing works fine, can i refactor the below JSX to properly maintain code.

 export default function HomePage() {
  
  const dispatch = useDispatch();
  const { sessionInfo, loading } = useSelector(state => state.session)
  
  const nextPath = (path) => {
    this.props.history.push(path);
  };
  
  React.useEffect(() => {
     dispatch(validateSession())
  }, [])
  
  const sessionValidation = (
    <>
      { loading ? 
        <Box textAlign="center" sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}> 
          <CircularProgress size={25} sx={{ mr: 2 }} />
          <Typography variant="h4">Validating session.. please wait</Typography>
        </Box> : 
         <Box textAlign="center" sx={{ justifyContent: 'center', alignItems: 'center' }}> 
         { sessionInfo && sessionInfo.code === 403 ? 
          <>
            <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
              <ErrorIcon fontSize="large" sx={{ mr: 1 }} color="error" />
              <Typography variant="h4">{"SESSION EXPIRED" }</Typography>
             </div>
             <Typography sx={{ textAlign: "center", mt: 2 }}>
              <Button component={Link} to = "/home" variant="contained" color="primary">
                Go back
             </Button>
             </Typography>
          </>
         : 
         <>
             <div>
             <CheckCircleIcon sx={{ mr: 1 }} color="success" />
             <Typography>{"SESSION VALIDATION SUCCEEDED" }</Typography>
             </div>
             <Typography sx={{ textAlign: "center", mt: 2 }}>
              <Link to = "/home">Get Started</Link>
              <Button component={Link} to = "/home" variant="contained" color="primary">
                Get Started
             </Button>
             </Typography>
         </>
         }
       </Box>
      }
    </>
  )
     
  return (
    <Container maxWidth="sm" sx={{ mt: 4 }}>
      <Paper elevation={1} sx={{ py: 4, borderTop: "4px solid #F76E40" }}>
         { sessionValidation }
      </Paper>
    </Container>
  );
}

Merge objects of array having same value of a key but keep different values of another key as inner array

I have an array which has keys eventId and selectedNumber. In the array same eventid can be present in multiple objects but selectedNumber value will be always different. My aim is to make a nested array in which each object will have unique eventId But selectedNumber will become an array having numbers from each of those objects having the same eventId. I tried using lodash _.groupBy() method but its just combines the objects into array and add it to the value with key as eventId. I don’t want that. Anyway to do it?

Input:--

[{
  "eventId" : "636939dde9341f2fbbc7256e",
  "selectedNumber" : "20"
},
{
  "eventId" : "636939dde9341f2fbbc7256e",
  "selectedNumber" : "30"
},
{
  "eventId" : "63693a55e9341f2fbbc725c0",
  "selectedNumber" : "50"
}]

Result:--


[{
  "eventId" : "636939dde9341f2fbbc7256e",
  "selectedNumber" : ["20", "30"]
},
{
  "eventId" : "63693a55e9341f2fbbc725c0",
  "selectedNumber" : "50"
}]

Prelaod external json in Helmet ReactJS

I’m trying to preload a JSON file from (S3 Bucket) Inside React-Helmet and access the object of this JSON inside ReactJS, please see below code, I have over 100 JSON files/articles and these articles should be accessible from S3, Also I have to preload the JSON file so that it can be crawled by search engines.

My question is how can I access the JSON file when is loaded without firing fetch request ?, I know if I fire fetch request or load the files from a local folder I’m able to access it, as I said before, I have a requirement where the files will grow, any help, would be appreciated it?

console.log("Accessing JSON objects ", data.object1);
 return(
   <> 
     <Helmet>   
       <link
        rel="preload"
        href="https://****.s3.me-central-1.amazonaws.com/prod/service2.json"
        as="fetch"
        type="application/json"
        crossorigin="anonymous"
      />
  </Helmet> 

Is there a memory leak in the nodejs code [closed]

I am looking for a memory leak in my nodejs application.

I have a suspect in the below code

const CRON_SCHEDULE = '*/15 * * * * *';


function myFunction() {
const  someBigString = "";   // This will cause an error (y is not defined)
}

function scehdule() {
return schedule(
            validate(CRON_SCHEDULE,
            () => this.myFunction()
        ));
}

I have a code called schedule which is called on the initialisation of the app which uses node-cron library to schedule a job every 15 mins which calls my function which has a fairly big string.

As i understand the string (someBigStrig) is in function/local scope so it should garbage collected.

Change Enter behaviour to Tab behaviour

I am trying this code

$ = jQuery.noConflict();
        
$(document).on('keypress',function(e) {
    if(e.which == 13) {
        document.getElementById("menu-1-145f6ca").tabIndex = "1";
        $(this).trigger("keydown", [9]);
//             alert("return pressed");
    }
});

Basically I want If I press enter to my wordpress website it works as a tab

Javascript/Typescipt : Array count issue

trying to generate a table report and display in table form, count of each rating based on date. Rating is based on 5. I have the object

const surveyReport = [{“SurveyDateTaken”:”2022-11-04T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”4″},{“Title”:”Feedback”,”AnswerKey”:”First Comment”}]},{“SurveyDateTaken”:”2022-11-04T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”3″},{“Title”:”Feedback”,”AnswerKey”:”3 star Comment”}]},{“SurveyDateTaken”:”2022-11-04T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”3″},{“Title”:”Feedback”,”AnswerKey”:”3 Star Rating”}]},{“SurveyDateTaken”:”2022-11-04T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”2″},{“Title”:”Feedback”,”AnswerKey”:”2 Star Rating”}]},{“SurveyDateTaken”:”2022-11-04T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”2″}]},{“SurveyDateTaken”:”2022-10-31T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”4″},{“Title”:”Feedback”,”AnswerKey”:”New UI looks good”}]},{“SurveyDateTaken”:”2022-10-31T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”4″},{“Title”:”Feedback”,”AnswerKey”:”star rating 4″}]},{“SurveyDateTaken”:”2022-10-31T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”1″},{“Title”:”Feedback”,”AnswerKey”:”Difficult to Navigate”}]},{“SurveyDateTaken”:”2022-10-31T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”3″},{“Title”:”Feedback”,”AnswerKey”:”Okay UI”}]},{“SurveyDateTaken”:”2022-11-04T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”5″}]},{“SurveyDateTaken”:”2022-11-04T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”2″},{“Title”:”Feedback”,”AnswerKey”:”two Star Rating”}]},{“SurveyDateTaken”:”2022-11-04T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”4″},{“Title”:”Feedback”,”AnswerKey”:”Easy payment site”}]},{“SurveyDateTaken”:”2022-10-15T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”2″}]},{“SurveyDateTaken”:”2022-11-03T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”5″},{“Title”:”Feedback”,”AnswerKey”:”Awesome”}]},{“SurveyDateTaken”:”2022-11-03T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”4″},{“Title”:”Feedback”,”AnswerKey”:”PS rocks”}]},{“SurveyDateTaken”:”2022-11-02T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”3″},{“Title”:”Feedback”,”AnswerKey”:”three Star Rating”}]},{“SurveyDateTaken”:”2022-11-02T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”5″},{“Title”:”Feedback”,”AnswerKey”:”Experian Rocks”}]},{“SurveyDateTaken”:”2022-11-01T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”4″},{“Title”:”Feedback”,”AnswerKey”:”4 Star Rating”}]},{“SurveyDateTaken”:”2022-11-01T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”4″},{“Title”:”Feedback”,”AnswerKey”:”Easy Payment Plan set up”}]},{“SurveyDateTaken”:”2022-10-29T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”4″},{“Title”:”Feedback”,”AnswerKey”:”Nice UI”}]},{“SurveyDateTaken”:”2022-10-29T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”5″},{“Title”:”Feedback”,”AnswerKey”:”Best UI”}]},{“SurveyDateTaken”:”2022-10-27T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”2″},{“Title”:”Feedback”,”AnswerKey”:”NOT UI FRIENDLY”}]},{“SurveyDateTaken”:”2022-10-27T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”4″},{“Title”:”Feedback”,”AnswerKey”:”Beautiful Colors”}]},{“SurveyDateTaken”:”2022-10-27T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”3″},{“Title”:”Feedback”,”AnswerKey”:”Colors are just OK”}]},{“SurveyDateTaken”:”2022-10-31T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”4″},{“Title”:”Feedback”,”AnswerKey”:”Nice Colors”}]},{“SurveyDateTaken”:”2022-11-01T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”4″}]},{“SurveyDateTaken”:”2022-11-02T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”5″}]},{“SurveyDateTaken”:”2022-11-03T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”3″}]},{“SurveyDateTaken”:”2022-11-04T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”3″}]},{“SurveyDateTaken”:”2022-11-04T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”3″},{“Title”:”Feedback”,”AnswerKey”:”3 stars”}]},{“SurveyDateTaken”:”2022-10-31T00:00:00″,”SurveyAnswers”:[{“Title”:”Star Rating”,”AnswerKey”:”3″},{“Title”:”Feedback”,”AnswerKey”:”Need Chat Support”}]}]

trying to generate a table, each row in the table should have cells with Table head: Date, 1 rating (count), 2 rating (count), 3 rating (count), 4 rating (count), 5 rating (count)

const group = (arr) => 
   Object.entries(arr.reduce((acc, { SurveyDateTaken, SurveyAnswers }) => {
      const [{ AnswerKey }] = SurveyAnswers;
      console.error('Ans', AnswerKey);
      (acc[SurveyDateTaken] || (acc[SurveyDateTaken] = [])).push(AnswerKey);
      return acc;
   }, {})).map<{SurveyDateTaken: string, Ratings: string[]}>(([date, rating ]) => ({ SurveyDateTaken: moment(date).format('MM/DD/YYYY'), Ratings: (rating as string[]) }));
   
const res = group(surveyReport);

const ratingCount = res.map(day => {
  const ratingCountObj = day.Ratings.reduce((acc, cur) => (acc[cur] ? acc[cur]++: acc[cur] = 1, acc), {});
  return {
    date: day.SurveyDateTaken,
    ratingCounts: Object.values(ratingCountObj)
  }
}
);

const renderCountRows = ( ratingCountPerDay ) => {

  return (
    <>
      <TableCell>{ratingCountPerDay.date}</TableCell>
      {ratingCountPerDay.ratingCounts.map((ratingCount) => (
        <TableCell style={{ textAlign: "right" }}>{ratingCount}</TableCell>
      ))}
    </>
  );
}

HTML:

<>
          <div> Rating Report </div>
          <>
          <Paper className={classes.paper}>
            <div className={classes.paperContainer}>
              <TableContainer>
                <Table className={classes.table} aria-label="customized table">
                  <TableHead>
                    <TableRow>
                      <StyledTableCell>Date Submitted</StyledTableCell>
                      <StyledTableCell align="right">1 Star</StyledTableCell>
                      <StyledTableCell align="right">2 Star</StyledTableCell>
                      <StyledTableCell align="right">3 Star</StyledTableCell>
                      <StyledTableCell align="right">4 Star</StyledTableCell>
                      <StyledTableCell align="right">5 Star</StyledTableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {ratingCount.map(rc => (
                      <TableRow key={rc.date}>
                        {renderCountRows(rc)}
                      </TableRow>
                    ) )}
                  </TableBody>
                </Table>
              </TableContainer>
            </div>
          </Paper>
        </>
        </>

the count of each star rating is incorrect. Need help where I’m going wrong

enter image description here