Comparing two arrays if they have the exact same values [duplicate]

I have a first array of objects, inside this array there are objects each containg a members array containing an x amount of userIds
In my second array, I have an array of userIds, I want to create a function that returns true or false if and only if the two arrays have the same entries.
Heres what I have tried:

const compareArrays = () => {
  if (usersConvos.some(convo=> JSON.stringify(convo.members)=== JSON.stringify(membersArray)) {
   return true
  }
  else {
   return false
  }
} 

This doesnt work any idea?

How to divide a value and distribute it on my html page?

Here’s the thing. Basicaly, i have two values on my html page, that i got from a form.
The person completes de amount of money they have on one input, and on the o ther input, the number of people.

So, my question is:
How do i divide the amount.value by the people.value, and distribute it, in a way it appears as shown in the example below?

Amount: 150 / Number of People: 3

-Person 1 - 50
-Person 2 - 50
-Person 3 - 50

And would it be possible to do the same, but making sure that the amount each one gets wouldn’t be distributed equaly? Like:

Amount: 150 / Number of People: 3

-Person 1 - 75 (50%)
-Person 2 - 45 (30%)
-Person 3 - 30 (20%)

JavaScript Multiple Sort with condition

const activeSorts = {
    aFirst: 0,
    zFirst: 0,
    cheapFirst: 1,
    expensiveFirst: 0,
};

const cards = somedata
        .sort(
            (activeSorts.cheapFirst && sortCheapFirst) ||
            (activeSorts.aFirst && sortAlphabet) ||
            (activeSorts.expensiveFirst && sortExpensiveFirst)
        );

I’m trying to sort data based on conditions in activeSorts. if a sort type value is 1, data should be sorted based on that, and if it’s 0, it shouldn’t.

The problem is that it requires me to have at least one sort enabled. If I make all of them 0, I get this:

TypeError: The comparison function must be either a function or undefined

What should I do?

Adding a working checkbox to a todo list using redux

i have made this todo list App using redux with the help of a tutorial for the sake of learning Redux architecture.
so the check box should work for every individual task added, but onChange i get all of the boxes values turning to true, when i figured i wasn’t mapping throw the state.
but then if you look into the logger on the console you see that i have got it working, only failing to display the check properly.
you can find the full code here [https://github.com/Faycal88/Todo-App]

this is the Task component

    return (
        
        <div style={{ display: 'flex', flexDirection: 'flex-start', justifyContent: 'space-evenly', border: '1px solid white', padding: '5px', width: '200px', cursor: 'pointer' }} >
            <input style={{ width: '1rem', height: '0.8rem', margin: '0', padding: '0' }} type="checkbox" checked={check} onChange={() => checkTodo(idx)} />
            <div onClick={() => editTodo(idx)} >
            {
                selected === idx ? text : todo
            } </div>
            <div style={{ cursor: 'pointer' }} onClick={() => deleteTodo(idx)}>x</div>
        </div>
            
            
    )
} ```

Here is the action.reducer 

``` export const checkTodo = key => ({
    type: "CHECK_TODO",
    payload: key
}) ``` 

and this is the reducer switch case (the check box part )

``` case 'CHECK_TODO':
            const todos5 = state.todos.map((todo, i) => { 
                if (i == action.payload) {
                    return { ...state, check: !todo.check ,text: todo}
                }
                return todo
            })
            setPersist(todos5)
            return {
                ...state,todos5
            } ``` 

https://github.com/Faycal88/Todo-App


  [1]: https://github.com/Faycal88/Todo-App

How to allow a function argument to dynamically only be one value from a typescript interface?

I am creating a theme handling function.

The function that has a desiredColor parameter. I want passed in argument to only be one of the keys from the interface provided as the type for the underlying colors.

Is there a way to restrict the desiredColor to only be one of the key values of the underlying interface?

(is there a way to do this without also having to maintain an adjacent enum?)

const handleThemeColors = (mode: ThemeMode): any => {
  const colorsHandler = (desiredColor: Array<keyof PaletteColors>) =>
  // goal ^ desiredColor can be either: blueDark, blueMain, or blueLight
 {
    switch (mode) {
      case 'light':
        return colorsLight[desiredColor];
      default:
        return colorsDark;
    }
  };
 ...
}
interface PaletteColors {
  blueDark: string;
  blueMain: string;
  blueLight: string;
}

const colorsLight: PaletteColors = {
  blueDark: 'rgba(2, 189, 185,1)',
  blueMain: 'rgba(0, 203, 198,1)',
  blueLight: 'rgba(147, 231, 229,1)'
}

How does JS understand props parameter as object in any function (react.js)?

While i am studying react.js, i noticed that any function i wrote and then give it any parameter name, javascript will understand this parameter as object type

Like this :

function Somthing(some){
    return (
        <div>
            Hello, friends{console.log(some)}
        </div> 
    ) 
}

expprt default Something

Then console.log(some) will give me “Object{}” type without assigning to it any object

So my question, How can i do this concept in vanilla javascript and how does javascript understand it?

Can you use a ‘hidden’ button to start something?

I am trying to have images appear on click of a button. I have that process working, but I’d like for the users/players to not see the buttons I will be clicking.

Is there a way to set a space where the button ‘still lives’ but isn’t visible?

I’m pretty sure I’m going to need to get cute and hide the buttons on screen. However, if i can set them to specific spots and have them invisible, but clickable, that would be ideal.

Thanks in advance for the help.

I’m using HTML, CSS and Java. There’s no JQuery in the code (for context)

puppeteer: How to automatically close browser when no activity detected

I am trying to make a single browser with automatically close when it does not have any action after three minutes, and the first challenge is about how to detect the browser is in using. And the second challenge is about how to set up a timer. I have some ideas about using the Debounce function with the event listener, but the most of function calls in puppeteer are async functions, so it gives me a lot of errors. So here is my question, what is the better to make this? Maybe an idea will help. Thank you.

Prevent toggleClass to be used on every element on the page

I have a function which, when clicking on a link with the class .show-more, opens up the div with the class .productinfo. Now, it also adds a class to the link itself (.active) – the problem what I have is that I have a few links on this page with the same class. I’ve managed to only open up the correct .productinfo when clicking on it, but the class will be added to every link nonetheless. Also tried adding the following to the code but that did not work:

$(this).find('show-more').toggleClass("active");

My structure is the following:

<div class="main-content">
<div class="col-1">Content 1</div>
<div class="col-2">Content 2</div>
<div class="col-3"><a class="show-more">Show more</a></div>
<div class="productinfo">This content is hidden and will be shown when clicked</div>
</div>

<div class="main-content">
<div class="col-1">Content 1</div>
<div class="col-2">Content 2</div>
<div class="col-3"><a class="show-more">Show more</a></div>
<div class="productinfo">This content is hidden and will be shown when clicked</div>
</div>

jQuery(document).ready(function($) {

            $('body').on('click', 'a.show-more', function(e) {
            e.preventDefault();
            $('.show-more').toggleClass("active");
            var $this = $(this).parents('.product');
            $this.find('.productinfo').toggle(0, 'slide')

});

});

Router.push() not working without any apparent reason

So I’m trying to create a simple login page that redirects to another page after checking credentials and setting a cookie. My API endpoint is working fine as tested with Postman. However, for some reason router.push isn’t working at all. It sometimes works when I mention a page that doesn’t exist, giving me a 404 error. But other than that I can’t figure out what’s wrong with my code.

I don’t see any errors on the console whatsoever either.

import axios from "axios"
import { useRouter } from "next/router"
import { useState } from "react"

export default function login() {

    const [username, setUsername] = useState(null)
    const [password, setPassword] = useState(null)
    const [error, setError] = useState(false)
    const router = useRouter()

    const handleClick = async () => {
        try {
          await axios.post("http://192.168.0.112:3000/api/login", {
            username,
            password,
          });
          router.push("/admin");
        } catch (err) {
          setError(true);
        }
      };
    

    return (
        <div className="container mt-5 d-flex flex-column justify-content-center align-items-center">
            <h1 className="display-3">Admin login</h1>
            <form className="bg-light p-3">
                <div className="mb-3">
                    <label htmlFor="username" className="form-label">Username</label>
                    <input type="text" className="form-control" id="username" onChange={(e) => setUsername(e.target.value)} name="username" aria-describedby="emailHelp"/>
                </div>
                <div className="mb-3">
                    <label htmlFor="password" className="form-label">Password</label>
                    <input type="password" className="form-control" id="password" onChange={(e) => setPassword(e.target.value)} name="password"/>
                </div>
                {error &&<span>Wrong Credentials</span>}
                <button className="btn btn-success" onClick={handleClick}>Log in</button>
            </form>
        </div>
    )
}

This page checks the credentials (from an env.local file) and creates a cookie if the credentials are right, but that’s about it. Any idea how I can get router.push to start working as expected?

Typescript “Element implicitly has an ‘any’ type because expression of type ‘Rank’ can’t be used to index type ‘IPowerCards'”

I am building a card game and have the following types:

type Rank = "A"| "2"| "3"| "4"| "5"| "6"| "7"| "8"| "9"| "T"| "J"| "Q"| "K";

interface IPowerCards {
  [key: Rank]: any
}

I also have the following object which I am trying to access with a rank string:

const powerCards: IPowerCards = {
  "A": {
    canPlayOnAnyCard: true,
    canChangeSuit: true,
  },
  "2": {
    canCounterPenaltyCard: true,
    penaltyAmount: 2,
  },
  ...,
};

All the keys on this object are valid Rank types. I am trying to access values on the powerCards object using the following code:

const rank = getRank(card) as Rank;
return rank && powerCards[rank]?.canCounterPenaltyCard

However, I get the error Element implicitly has an 'any' type because expression of type 'Rank' can't be used to index type 'IPowerCards'. Property 'A' does not exist on type 'IPowerCards'.
This error message doesn’t make sense to me because I am ensuring that the rank variable, which is the variable I am using to access the powerCards object, is of Rank type, which is what I have specified in my IPowerCards type definition. Where am I going wrong? Thanks

ReactMarkdown not working with React Syntax Highlighter

how are you? I’m building a blog and using ReactMarkdown, and I want to render a custom component for the code blocks like this:

<ReactMarkdown
   children={content}
   rehypePlugins={[rehypeRaw]}
   components={{
     code({ node, inline, children, className, ...props }) {
          return <PrismHighlighter children={children}  {...props} />;
          }
    }}
/>

And my ‘PrismHighlighter’ file consists in the following:

import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { nightOwl } from 'react-syntax-highlighter/dist/cjs/styles/prism';

const SyntaxHighlight = ({ props, children }) => (
  <SyntaxHighlighter style={nightOwl} language="javascript" showLineNumbers {...props}>
    {children}
  </SyntaxHighlighter>
);

export default SyntaxHighlight;

The problem is the following: ReactMarkdown is receiving a string for the code (what is okay), like this:

nucleus_dataset =
nucleus.create_dataset("PennFudan") DATASET_ID =
nucleus_dataset.info()['dataset_id'] # Save unique ID for future use

def format_img_data_for_upload(img_dir: str): """Instantiates a
Nucleus DatasetItem for all images in the PennFudan dataset.

Parameters ---------- img_dir : str
The filepath to the image directory

Returns ------- List[DatasetItem]
A list of DatasetItem that can be uploaded via the Nucleus API """ img_list = [] for img_filename in os.listdir(img_dir):
img_id = img_filename.split('.')[0]
item = DatasetItem(
image_location=os.path.join(img_dir, img_filename),
reference_id=img_id,
)
img_list.append(item) return img_list

img_list = format_img_data_for_upload(IMG_DIR)

response = nucleus_dataset.append(img_list)

But ReactMarkdown sends to PrismHighlighter an array of objects, like this:
example of what ReactMarkdown sends

This results of PrismHighlighter avoiding several lines and showing only half or less of the code, like this:
example

So, does anyone knows what happening here? I’m struggling with this for days now. Thanks!

Scroll to the last item of a mapped array

I have a Message component that displays all the messages(incoming and outgoing) in one thread.

I would like the last message/a newly typed message/incoming message to always appear at the bottom of the conversation. Kind of like what all chats/messaging apps do.

Here is my code:

import React, { useRef } from "react";

const dummy = useRef();

...

dummy?.current?.scrollIntoView(true, {
    behaviour: "auto",
});

... 

<div className="">
  <Paper
    elevation={0}
    sx={{
      backgroundColor: "#fafafa",
      maxHeight: 200,
      overflow: "auto",
    }}
  >
    {messages.map((message, idx) => (
      <div key={idx} ref={dummy}>
        <Message message={message} name={name} />
      </div>
    ))}
    {/* I tried this also
    <div ref={dummy}></div> */}
  </Paper>
</div>

I want all the messages that can fit in the maxHeight: 200 to be displayed with the last message just at the bottom when I click on the conversation/thread. Currently, the WHOLE page scrolls to bottom instead of just the messages in the thread. The page should remain stationary.

How do I do this?