Need help in understanding this javascript code [duplicate]

Help in understanding below line:
return { …acc, [firstLetter]: […(acc[firstLetter] || []), cur] };

// Write a function that takes an array of strings as argument
// Group those strings by their first letter
// Return an object that contains properties with keys representing first letters
// The values should be arrays of strings containing only the corresponding strings
// For example, the array [‘Alf’, ‘Alice’, ‘Ben’] should be transformed to
// { a: [‘Alf’, ‘Alice’], b: [‘Ben’]}

function myFunction(arr) {
  return arr.reduce((acc, cur) => {
  const firstLetter = cur.toLowerCase().charAt(0);
  return { ...acc, [firstLetter]: [...(acc[firstLetter] || []), 
  cur] };
  }, {});
  }

Test Cases:

myFunction([‘Alf’, ‘Alice’, ‘Ben’])
Expected { a: [‘Alf’, ‘Alice’], b: [‘Ben’]}

myFunction([‘Ant’, ‘Bear’, ‘Bird’])
Expected { a: [‘Ant’], b: [‘Bear’, ‘Bird’]}

myFunction([‘Berlin’, ‘Paris’, ‘Prague’])
Expected { b: [‘Berlin’], p: [‘Paris’, ‘Prague’]}

How to do a for loop in a array with a index that contain object

I’m trying to do a for loop in a array like this:

 a0C7X0000056xmxUAA: {
   attributes: {
     type: 'GRD__c',
     url: '/services/data/v53.0/sobjects/GRD__c/a0C7X0000056xmxUAA'
   },
   Id: 'a0C7X0000056xmxUAA',
   Name: 'Lote-6155066',
   Guia__c: [ a0Y7X000006RUHxUAO: [Object], a0Y7X000006RUI2UAO: [Object] ]
 },
 a0C7X0000056x9EUAQ: {
   attributes: {
     type: 'GRD__c',
     url: '/services/data/v53.0/sobjects/GRD__c/a0C7X0000056x9EUAQ'
   },
   Id: 'a0C7X0000056x9EUAQ',
   Name: 'Lote-6155065',
   Guia__c: []
 },
 a0C7X0000056x99UAA: {
   attributes: {
     type: 'GRD__c',
     url: '/services/data/v53.0/sobjects/GRD__c/a0C7X0000056x99UAA'
   },
   Id: 'a0C7X0000056x99UAA',
   Name: 'Lote-6155064',
   Guia__c: [
     a0Y7X000006RSSvUAO: [Object],
     a0Y7X000006RST0UAO: [Object],
     a0Y7X000006RST1UAO: [Object]
   ]
 },
 a0C7X0000056x8YUAQ: {
   attributes: {
     type: 'GRD__c',
     url: '/services/data/v53.0/sobjects/GRD__c/a0C7X0000056x8YUAQ'
   },
   Id: 'a0C7X0000056x8YUAQ',
   Name: 'Lote-6155063',
   Guia__c: [ a0Y7X000006RSR9UAO: [Object], a0Y7X000006RSREUA4: [Object] ]
 },
 a0C7X0000056wmxUAA: {
   attributes: {
     type: 'GRD__c',
     url: '/services/data/v53.0/sobjects/GRD__c/a0C7X0000056wmxUAA'
   },
   Id: 'a0C7X0000056wmxUAA',
   Name: 'Lote-6155062',
   Guia__c: [ a0Y7X000006RSR4UAO: [Object] ]
 },
 a0C7X0000056wmsUAA: {
   attributes: {
     type: 'GRD__c',
     url: '/services/data/v53.0/sobjects/GRD__c/a0C7X0000056wmsUAA'
   },
   Id: 'a0C7X0000056wmsUAA',
   Name: 'Lote-6155061',
   Guia__c: [ a0Y7X000006RSQzUAO: [Object] ]
 },
 a0C7X0000056wmnUAA: {
   attributes: {
     type: 'GRD__c',
     url: '/services/data/v53.0/sobjects/GRD__c/a0C7X0000056wmnUAA'
   },
   Id: 'a0C7X0000056wmnUAA',
   Name: 'Lote-6155060',
   Guia__c: [ a0Y7X000006RSQpUAO: [Object], a0Y7X000006RSQuUAO: [Object] ]
 },
 a0C7X0000056wmYUAQ: {
   attributes: {
     type: 'GRD__c',
     url: '/services/data/v53.0/sobjects/GRD__c/a0C7X0000056wmYUAQ'
   },
   Id: 'a0C7X0000056wmYUAQ',
   Name: 'Lote-6155059',
   Guia__c: [ a0Y7X000006RSQLUA4: [Object], a0Y7X000006RSQQUA4: [Object] ]
 },
 a0C7X0000056wmTUAQ: {
   attributes: {
     type: 'GRD__c',
     url: '/services/data/v53.0/sobjects/GRD__c/a0C7X0000056wmTUAQ'
   },
   Id: 'a0C7X0000056wmTUAQ',
   Name: 'Lote-6155058',
   Guia__c: [
     a0Y7X000006RSQGUA4: [Object],
     a0Y7X000006RSQVUA4: [Object],
     a0Y7X000006RSQaUAO: [Object],
     a0Y7X000006RSQfUAO: [Object],
     a0Y7X000006RSQkUAO: [Object]
   ]
 },
 a0C7X0000056wmOUAQ: {
   attributes: {
     type: 'GRD__c',
     url: '/services/data/v53.0/sobjects/GRD__c/a0C7X0000056wmOUAQ'
   },
   Id: 'a0C7X0000056wmOUAQ',
   Name: 'Lote-6155057',
   Guia__c: [ a0Y7X000006RSQBUA4: [Object] ]
 }
]

but when I try to do a loop nothing happens, i’m doing like this because during the execution i need to add new keys like Guia__c and inside of Guia__c i need to put i new one, this already happen but the problem is to do the loop, and when i try to convert the array to a string nothing returns

Ajax Parameter Being Received as {string[0[} in MVC Controller

First of all, I have never successfully built an AJAX call that worked. This is my first real try at doing this.

I am working on building a function to update existing records in a SQL database. I am using ASP.NET Core (.NET 6) MVC but I also use JavaScript and jQuery. I cannot have the page refresh, so I need to use ajax to contact the Controller and update the records.

I have an array that was converted from a NodeList. When I debug step by step, the collectionsArray looks perfectly fine and has data in it.

//Create array based on the collections list
    const collectionsArray = Array.from(collectionList);

    $.ajax({
        method: 'POST',
        url: '/Collections/UpdateCollectionSortOrder',
        data: collectionsArray,
    })
        .done(function (msg) {
            alert('Sent');
        });

However, when I run the application and debug the code, the array is received in the Controller as {string[0]}.

Here is the method which is in the Controller, with my mouse hovered over the parameter:

enter image description here

Do not pay attention to the rest of the code in the controller method. I have not really written anything in there of importance yet. I plan to do that once the data is correctly transferred to the Controller.

I have tried dozens of ideas including what you see in the Controller with the serialize function, just to see if it processes the junk data that is getting passed, but it hasn’t made a difference.

I have been Googling the issue & reading other StackOverflow posts. I’ve tried things like adding/changing contentType, dataType, adding ‘traditional: true‘, using JSON.stringify, putting ‘data: { collections: collectionsArray }‘ in a dozen different formats. I tried processing it as a GET instead of POST, I tried using params.

I am out of ideas. Things that have worked for others are not working for me. What am I doing wrong? I’m sure it’s something minor.

Javascript function for game sensitivity converter is not working on my web

I am a final year highschool. For my project, we decided to make front-end css for our game sensitivity converter website.

I have copied code from this website https://sensitivityconverter.com/

But on jsfiddle, my code is not working. I can see the form but I couldn’t figure out how to make the calculation works like on original website.

https://jsfiddle.net/60jyo4hz/ enter code here

Please forgive me for my poor grammar.

Hide show depending on drop down section if selection and class have multiple words

How can I change my java scrip to work if the selected has multiple words, for example bellow the value has two words “Online Events” the div class is two words “Online Events” however it will remain hidden as the current Jquery will only look for the value if matches the class as one word.

let $j = jQuery.noConflict();

$j(document).ready(function($j) {
  $j("#event-drop").change(function() {
    let opt = $j(this).val();
    if (opt === "all") {
      $j(".event_div").show();
    } else {
      $j(".event_div").hide();
      $j("." + opt).show();
    }
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="event-drop" style="margin-bottom:20px">
  <option value="all">All</option>
  <option value="Online Events">online</option>
  <option value="Ofline Events">online</option>
</select>

<div class="card-deck col-4 pb-5 Online Events event_div" style="">
  <div class="card top-line-grey">
    <small class="card-header bg-transparent border-0 font-weight-bold text-uppercase" style="color: #8D8CAB">here titlke</small>
    <div class="card-body">
      <h5 class="card-title text-capitalize pb-2">Sub title</h5>
    </div>
    <div class="card-footer bg-transparent border-0">
      <small class="float-left font-weight-bold text-uppercase">
                                            small text                                            </small>
      <small class="float-right font-weight-bold text-uppercase">
                                                January 4, 2022                                            </small>
    </div>
    <div class="card-footer bg-transparent border-0">
      <a class="btn-link text-uppercase" href="http://www.google.com" target="_blank">
                                                    More info                                                </a>
    </div>
  </div>
</div>

somehow two intervals run simultaneously, despite the first one being cleared

In the code:

let nextInterval = function(){  
    if(score % 10 === 0) {
        speed -= 10;
    }
    if(internalScore === 20) {
        clearInterval(2);
        catchingEggs();
    }
    if(heartIndex<0) {
        clearInterval(2);
        return
    }
    eggIndex = Math.floor(Math.random()*4); 
    fallingEggs(allEggs[eggIndex], speed);
    }

setInterval(function(){  
    if(score % 10 === 0) {
        speed -= 10;
    }
    if(internalScore === 20) {
        clearInterval(1);
        setInterval (nextInterval,speed*3.5);
        return
    }
    if(heartIndex<0) {
        clearInterval(1);
        return
    }
    eggIndex = Math.floor(Math.random()*4); 
    fallingEggs(allEggs[eggIndex], speed);
    }, speed*3.5); 

when internalScore === 20 both intervals start running together, simultaneously. I use clearInterval() to stop the interval with ID 1, but as the nextInterval starts, the first one starts again.

I want to be able to reuse the same interval code (ideally with different variables). I tried starting new interval outside the function and upon a conditional, but that didn’t work either, JS simply goes through the code once, sees the conditional === false and don’t call second interval at all and if i put that conditional in a while loop, it crashes the browser.

so the above code is the closest i got to what i’m trying to do, but still not quite there.

What happens if you set an Array with a JSON Object value?

I’m struggling with a big JSON Object and I got into a weird problem:
My Object has the following structure:

const bar = {
  arr: []
}

If I try to set its value in this way bar.arr.foo = 'ciao' it doesn’t give me any error. The result object is this

enter image description here

What is that strange “Array(0)” that the Chrome dev tools are pointing out? If I try to type typeof bar.arr it says “object”

But doing JSON.stringify(bar, null, 2) results in '{n "arr": []n}'

CCI Logistics CCI Logistics – Intime Intact – CCI Logistics

Website URL – https://cci-logistics.com/
Website and Company Name – CCI Logistics
Website Bio – CCIL specializes in customized transport solutions, with competency in road and rail while air is managed through various partner organizations.
No- +91-022 6781 8500
Email –[email protected]
add- 202-B, Corporate Center,
Andheri – Kurla Road,
Marol Pipeline, Andheri East,
Mumbai – 400059. INDIA

How to get this subcollection’s ref id in firestore

I am trying to get this subcollection’s ref id
[1]: https://i.stack.imgur.com/4Ato6.png
I am following this tutorial however :
[2]: https://www.pluralsight.com/guides/consume-data-from-firebase-firestore-in-a-react-app
I want to get the hBYWvZ3KN3NLLrucTpryeTQZnHz2 from the firestore :

 const HighlightDbId =  await db.collection('highlights').doc('2SCS2S0JnzngWEiYkHNk').collection('hBYWvZ3KN3NLLrucTpryeTQZnHz2')

Please how can I possible get that id ??

React update state filter object array

I want to filter my object array, which I fetched from DB.

const [loadedCars, setLoadedCars] = useState();

useEffect(() => {
      setLoading(true);
      axios
        .get(process.env.REACT_APP_BACKEND_URL + "/cars/", {
          headers: {
            Authorization: "Bearer " + auth.token,
            "Content-Type": "application/json",
          },
        })
        .then((res) => {
          console.log(res.data.cars);
          setLoadedCars(res.data.cars);
          setLoading(false);
        });
  
  }, [auth.token]);

My code for Search likes that

const searchHandle = (e) => {
    e.preventDefault();
    setDates(share.date_ranges);
    const filtered = loadedCars.filter((item) => !checker(item.dates, share.date_ranges));
    console.log(filtered);
    setLoadedCars(filtered)
  };

<Button onClick={searchHandle} className="search-btn" inverse>Search</Button>

Filter works just for one time. When I want to search a few times, it is not updated. And in the end my object array became empty.

How can I update my state? Thanks for help.

Finding and trying to understand the technology used behind the scene

Sorry if the question is a bit out of place but don’t know any better since i’m a complete beginner.

What i’m trying to say is let’s take for example this site

https://exp-ion.lusion.co/

I am trying to “decode” what libraries and technologies are used behind the scene so i can learn more about them and try to replicate the same effects.
Is it in any way possible to get “hints” on how things are done?

Tried looking up the source code, tried inspecting various elements. I get that the scene is done using threejs library. What about the scroll ladder? What about the text?

Thank you in advance for any tips and tricks.

Can a app be made with HTML, CSS, and Javascript?

So I really like programming with HTML5, CSS, and JS. I’m relatively new to it. I was wondering if it is possible to make apps with HTML5, CSS, and JS. If so how could I put a project into app form and what courses would you recommend as I am probably still considered a beginner in JS.

Intersection observer Hook doesn’t work when threshold is set to 1 on google chrome

I am trying to make Intersection observer so I can implement infinity scroll in my react app. I decided to create a hook “useInfinityScroll” which accepts ref as prop, and by using intersection observer with threshold of 1 I wanted to be notified when user is intersecting with that ref. But for some reason when user scrolls to selected element and satisfies threshold requirement still “isIntersecting” is not equal to “true” value. And thats only the case for google chrome on my mac, it works fine with mozilla and with chrome on pc.

Here is my hook

import {useCallback, useEffect, useState} from "react";
import {not} from "ramda";

export function useInfinityScrollObserver(ref) {

    let [isVisible, setIsVisible] = useState(false);

    const handleIntersection = useCallback(([entry]) => {
        if (entry.isIntersecting){
            setIsVisible(true)
        }else if (not(entry.isIntersecting)){
            setIsVisible(false)
        }
    }, [])


    useEffect(() => {

        const options = {
            threshold: 1
        }

        // Create the observer, passing in the callback
        const observer = new IntersectionObserver(handleIntersection, options);

        // If we have a ref value, start observing it
        if (ref.current) {
            observer.observe(ref.current);
        }

        // If unmounting, disconnect the observer
        return () => {
            observer.unobserve(ref.current)
            observer.disconnect();
        }
    }, [ref,handleIntersection]);

    return isVisible;
}

Here is component where I use it:

import {useInfinityScrollObserver} from "../../hooks/useInfinityScrollObserver";
import {useEffect, useRef, useState} from "react";


const CountriesSection = () => {

    const sectionRef = useRef(null);
    const isVisible = useInfinityScrollObserver(sectionRef)

    useEffect(() => {
        if (isVisible){
            console.log("IS VISIBLE")
        }
    }, [isVisible])





    return (
        <section ref={sectionRef} className={styles['section-countries']}>


        </section>
    )

}

export default CountriesSection;

How to send data read from file as response from an express route in NodeJS?

I have a JSON file in local folder with a structure like this.

{
   license: "abcd",
   name: "abcd",

   data: [
      Array of JSON Objects ....
   ]
}

I want to access the data array in the Object and send it as response from express route
This is what I tried.

import express from "express";
import fs from "fs";
import bodyParser from "body-parser";

var app = express();
app.use(bodyParser.json());

var fileData: string = fs.readFileSync("path to json file", { encoding: 'utf-8' });
var jsonData = JSON.parse(fileData).data;

console.log(jsonData);

app.get("/getJsonData", (err, res) => {
    if (err)
        throw err;

    res.send(JSON.stringify(jsonData));
});

app.listen("3001", () => console.log("listening at 3001"));

It shows correct json when I log it outside the express route function, but inside the function the response is [object Object] with status code of 500 (Internal Server Error).

I tried the asynchronous method also

var app = express();
app.use(bodyParser.json());

app.get("/getJsonData", (err, res) => {
    if (err)
        throw err;

    fs.readFile("path to json file", (fileErr, result) => {
        if(fileErr) throw fileErr;

        var jsonData = JSON.parse(result.toString()).data;

        res.json(jsonData);
    });
    
});

but I get the same response as [object Object] and status code 500.
I tried res.send(JSON.stringify(jsonData)) but no use.
How can I send the json data that I get from file to frontend using Express??
btw I am using TypeScript for this.