how should javascript array control be

there is an array data as below.
I will have a nav. operation on the incoming data data in the array, otherwise I will print the data it is, I wonder how can I do this?`

title: item.title,

if item.title in the incoming data nav. If there is
Let this.$t(item.title) pass the print check. but if there is no nav. then check if this.$t(item.title)

menu_items: [
        {
          title: 'nav.home',
          path: '/',
          Index: 0
        },
        {
          title: 'nav.gallery',
          path: '/gallery',
          order: 10
        },
        {
          title: 'nav.contact',
          path: '/contact',
          order: 12
        },
        {
          title: 'hello',
          path: '/hello',
          order: 13
        },
        {
          title: 'hello2',
          path: '/hello2',
          order: 14
        }
      ]
menuItem() {
      return this.menu_items.map(item => {
        return {
          title: item.title,
          path: item.path,
          children: item.children,
          order: item.order
        }
      }).sort((a, b) => a.order - b.order)
    }

I am trying to use .replaceChild to replace an ordered list item with the value of a prompt

In my program it lists three items in an ordered list which all have ids. Then when you click a button it prompts you to enter the number corresponding to which numbered item on the list you want to replace. Then another prompt asks what you want to replace the text on the screen with. I have if statements set up to check for which number is entered and using .replaceChild to replace text in the list with the text entered in the prompt. I assumed this would work similar to how using .innerHTML does in replacing text, but it is not working for me. Any help would be appreciated.

Here is my code.

function replaceItem() 
{ 
var listNum = prompt("Which item are you replaceing 1, 2 or 3?");
var newItem = prompt("What is the name of the new item?");

if (listNum === 1) {
var item_one = document.getElementbyId("item1");
item_one.replaceChild(newItem, item_one);
}

if (listNum === 2) {
var item_two = document.getElementbyId("item2");
item_two.replaceChild(newItem, item_two);
}

if (listNum === 3) {
var item_three = document.getElementbyId("item3");
item_three.replaceChild(newItem, item_three);
}

}

HTML.

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Island Scenario</title>
</head>

<body>
<h3>You are being sent to an island by yourself to survive for 1 week.</h3> <br>
<h3>You are allowed to bring the clothes on your back but are also being given three items.</h3> <br>
<h3>Out of the three items that you are initially given, you are allowed to switch out one of the items for something of your choice.</h3> <br>
<h4>Here are your current items.</h4>
<ul>
<li id="item1">Water Bottle</li>
<li id="item2">Lighter</li>
<li id="item3">Backpack</li>
</ul>
<p>Click the button to replace an item.</p>
<button onclick="replaceItem();">Click Me</button>
</body>
</html>

Get pathname of from where user clicked in Next.JS

I have a button in a <Nav/> component that is shared between two components.
when the button is clicked it opens up a <FileUpload/> component.

<FileUpload/> can be accessed from:

<Profile /> => routes to '/profile'

<Home /> => routes to '/home'

inside <FileUpload/> is there any way to check which route the user has just come from?

so inside the <FileUpload/> component I can see:

`user has just come from ${route} route` => either /profile or /home

Value set for textArea is getting reverted/going empty while using script to fill form (AngelList Website)

I am trying to apply for a job using js in console, but when I try to set the textArea value in the form and click submit, it doesn’t work with the error being textArea empty.

Here is a gif :
gif showing issue

In the first command I am setting the value, in second, I click the second button, but it is not working.

Steps to reproduce:

Open any job on angel.co/jobs and then click apply then this form would appear, then using javascript select the input field, and set it’s value, and then click on submit button.

My commands: (classNames might be different for you)

Selecting the input field:

let eee = document.getElementsByClassName('styles_component__mqUU9 styles_component__kpbt6 styles_bordered__2C24K styles_width100__2VCHt styles_warning__3-xYH')

Setting value for input :

eee[0].value=`Hi, Nao

Submit button clicking:

document.getElementsByClassName('styles_component__3A0_k styles_primary__3xZwV styles_regular__3b1-C styles_emphasis__KRjK8 styles_component__sMuDw styles_medium__R1A06')[0].click();

I have tried: innerText, innerHtml, and adding event listener with keyboard events, but no luck. (not sure if I did keyboard events correctly or not but that didn’t work.

Any help or suggestions are highly appreciated.


PS:

Here is how I did keyboard events (inspired by this answer on stackoverflow):

Selecting the button and adding event listener to it.

let iButton = document.getElementsByClassName('styles_component__3A0_k styles_primary__3xZwV styles_regular__3b1-C styles_emphasis__KRjK8 styles_component__sMuDw styles_medium__R1A06');

iButton[0].addEventListener('click', simulateInput);
function simulateInput() {
  var inp = document.getElementsByClassName('styles_component__mqUU9 styles_component__kpbt6 styles_bordered__2C24K styles_width100__2VCHt styles_warning__3-xYH')[0];
  var ev = new Event('input');
  
  inp.value ='hello new input';
  inp.dispatchEvent(ev);
} 

How to calculate difference of two arrays with same value at second position

I’ve got a git diff output string parsed to this array, which gives me all changed dependencies in a package.json file:

const data = [
    [ '-', '@date-io/moment', '1.3.13', '1', '3', '13' ],
    [ '+', '@date-io/moment', '1.3.14', '1', '3', '14' ],
    [ '-', '@emotion/react', '11.7.0', '11', '7', '0' ],
    [ '-', '@emotion/styled', '11.6.0', '11', '6', '0' ],
    [ '+', '@emotion/react', '11.8.2', '11', '8', '2' ],
    [ '+', '@emotion/styled', '11.8.1', '11', '8', '1' ]
]

The first element (+/ -) shows me if this change was added or deleted. The second element is the package name (this is the element, which connects two arrays), and the next fields give me the version.
Now I need to iterate this array to find out which kind of version change has been made for each package. So the output should be:

{
    '@date-io/moment': 'patch',
    '@emotion/react': 'minor',
    '@emotion/react': 'minor'
}

I tried to get all packages by doing

const result = {}
data.forEach(d => {
    result[d[1]] = bump // how to calculate `bump`?
})

But this doesn’t handle + and - and it doesn’t calculate the type of version bump.

React too many re-renders when create an array with UseState

I’m trying to create a quiz to return the data based on selected checkboxes, the best option I find to do it is creating an array with index of every selected items but when I try to render page I receive the error of too many re-renders.

I have a JSON with some questions and the answers and I’m tryng to retrieve the list index of all selected answers and after compare with my JSON to return the right answer.

import "./questions.scss"
import React, { useState, useEffect, useRef} from 'react';
import { HashLink as Link } from 'react-router-hash-link';


export default function Questions({ data}) {
const [error, setError] = useState('');
const radiosWrapper = useRef();
const [updateCheckedState, setUpdateCheckedState] = useState([]);
const [temperament, SetTemperament] = useState('');
console.log(updateCheckedState);


useEffect(() => {
radiosWrapper.current.querySelectorAll('input:checked').forEach( el => el.checked = false );
}, [data]);

const changeHandler = (position) => {
      if(!updateCheckedState.includes(position)){
        setUpdateCheckedState( arr => [...arr, position])
    }else if(updateCheckedState.includes(position)){
      const index = updateCheckedState.indexOf(position);
      setUpdateCheckedState(updateCheckedState.splice(index, 1));
    }

    const sanguine = data.sanguine.filter(e => updateCheckedState.includes(e));
    const choleric = data.choleric.filter(e => updateCheckedState.includes(e));
    const melancholic = data.melancholic.filter(e => updateCheckedState.includes(e));
    const phlegmatic = data.phlegmatic.filter(e => updateCheckedState.includes(e));

    const result = Math.max(sanguine.length,choleric.length,melancholic.length,phlegmatic.length);
    
    switch(result){
      case sanguine.length:
        SetTemperament('/sanguine');
        break;
      case choleric.length:
        SetTemperament('/choleric');
        break;
      case melancholic.length:
        SetTemperament('/melancholic');
        break;
      case phlegmatic.length:
        SetTemperament('/phlegmatic');
        break;
      default:
    }

  if(error) {
    setError('');
  }
}

return(
  <div className="card">
    <div className="card-content">
      <div className="content">
        <h2 className="mb-5">{data.question}</h2>
        <div className="control" ref={radiosWrapper}>
          {data.choices.answer.map((choice, i) => (
            <label className="radio has-background-light" key={i}>
              <input type="checkbox" name="answer" value={choice} onChange={changeHandler(i)} />
              {choice}
            </label>
          ))}
        </div>
        {error && <div className="has-text-danger">{error}</div>}
        <Link className="link" to={temperament}>Resultado</Link>
      </div>
    </div>
  </div>
);

}

Changing only single element class in react

So I have a problem with this one. I need this class “active” to be added only to single li element onClick. I understand I need to get id of the exact li element that is clicked but I not sure on how to do that. Also I would like the first li element (Home) to be active on the begining once the page launches.
Here is the code I have for now:

import React, { useState, useEffect } from "react";

function NavBar() {
  const [isActive, setActive] = useState("false");

  const handleToggle = () => {
    setActive(!isActive);
  };

  return (
    <section id="main">
      <div className="navigation">
        <ul>
          <li
            onClick={handleToggle}
            className={`list${isActive ? " active" : ""}`}
          >
            <a href="#">
              <span className="icon">
                <ion-icon name="home-outline"></ion-icon>
              </span>
              <span className="text">Home</span>
            </a>
          </li>
          <li
            onClick={handleToggle}
            className={`list${isActive ? " active" : ""}`}
          >
            <a href="#">
              <span className="icon">
                <ion-icon name="person-outline"></ion-icon>
              </span>
              <span className="text">Profile</span>
            </a>
          </li>
          <li
            onClick={handleToggle}
            className={`list${isActive ? " active" : ""}`}
          >
            <a href="#">
              <span className="icon">
                <ion-icon name="chatbubble-outline"></ion-icon>
              </span>
              <span className="text">Mesaages</span>
            </a>
          </li>
          <li
            onClick={handleToggle}
            className={`list${isActive ? " active" : ""}`}
          >
            <a href="#">
              <span className="icon">
                <ion-icon name="camera-outline"></ion-icon>
              </span>
              <span className="text">Photos</span>
            </a>
          </li>
          <li
            onClick={handleToggle}
            className={`list${isActive ? " active" : ""}`}
          >
            <a href="#">
              <span className="icon">
                <ion-icon name="settings-outline"></ion-icon>
              </span>
              <span className="text">Settings</span>
            </a>
          </li>
          <div className="indicator"></div>
        </ul>
      </div>
    </section>
  );
}
export default NavBar;

Thank you in advance.

Identify the existence of a wall like structure in a given int array

The idea is that I will query an API endpoint which will return me an array consisting of a price value and a quantity value [price, quantity].

In this dataset there is high possibility that there are structure of values where there is a sudden increase in quantity for a limited but no small amount of price change basically a wall like structure.

Example below shows a range of price values and a quantity value as a heatmap. If I were to get a dataset of this area, I am interested in identifying the large, light colored, wall like structure. I have thought about brute forcing for every x amount of price and trying to find a sudden change in quantity and later try to look around it to find the extent of this wall but this just doesn’t feel like the right approach to me.

Is there any other algorithm or way that comes to mind for searching for this kind of data? Consider that the dataset it small enough to fit into memory and there is no rate limits for pulling from the API.

JavaScript don’t execute in html file

im trying to execute a js script on my web page to verify the entry in form before putting it on data base but it don’t work, the forum accept everything i put even its wrong

thats my js code i put it in head ( i tried putting it in body too but the same problem)

<script>
    function test() {
      name=f.name.value;
      email=f.email.value;
      phone=f.phone.value;
      for (i=0;i< length(name) ;i++){
        if(name.charAt(name[i])<'a' || nom.charAt(name[i])>'z' || name.charAt(name[i])<'A' || name.charAt(name[i])>'Z')
          {
            alert("verify your name");
            return false;
          }
        }
  
        if (isNaN(phone) || phone.length!=8  )
            {
            alert("verify your phone number");
            return false;
            }
            at=email.indexOf('@')
            point=email.indexOf('.',at)
        if(email=="" || at==-1 || point==-1)
        {
            alert("verify your email");
            return false;
        } 
  
      }
  </script>

and that’s the form code in html

<form action="add.php" method="POST" role="form" class="php-email-form" data-aos="fade-up" data-aos-delay="100" name='f'  onsubmit='return test()'>
          <div class="row">
            <div class="col-lg-4 col-md-6 form-group">
              <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars">
              <div class="validate"></div>
            </div>
            <div class="col-lg-4 col-md-6 form-group mt-3 mt-md-0">
              <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email">
              <div class="validate"></div>
            </div>
            <div class="col-lg-4 col-md-6 form-group mt-3 mt-md-0">
              <input type="text" class="form-control" name="phone" id="phone" placeholder="Your Phone" data-rule="minlen:4" data-msg="Please enter at least 4 chars">
              <div class="validate"></div>
            </div>
            <div class="col-lg-4 col-md-6 form-group mt-3">
              <input type="date" name="date" class="form-control" id="date" placeholder="Date" data-rule="minlen:4" data-msg="Please enter at least 4 chars">
              <div class="validate"></div>
            </div>
            <div class="col-lg-4 col-md-6 form-group mt-3">
              <input type="time" class="form-control" name="time" id="time" placeholder="Time" data-rule="minlen:4" data-msg="Please enter at least 4 chars">
              <div class="validate"></div>
            </div>
            <div class="col-lg-4 col-md-6 form-group mt-3">
              <input type="number" class="form-control" name="people" id="people" placeholder="# of people" data-rule="minlen:1" data-msg="Please enter at least 1 chars">
              <div class="validate"></div>
            </div>
          </div>
          <div class="form-group mt-3">
            <textarea class="form-control" name="message" rows="5" placeholder="Message"></textarea>
            <div class="validate"></div>
          </div>
          <div class="mb-3">
          </div><div class="text-center"><button onclick="test()" type="submit" name="ok">Book a table</button></div>
        </form>

How can I take the original image size in reactnavie conditional rendering?

The PostList function is a component inside FlatList.

When I have an item.Image, I want the Image to occupy that size with conditional rendering and push item.content

But with my code, it doesn’t take up as wide as the Image due to item.content. like this Screenshot the green one is Image width

enter image description here

How can I push the item.content when the item.Image is present while the Image takes up its normal width?

this is my code

        const PostList = ({item}: Props) => {


          return (
            <>
              <View style={styles.main}>
                <View style={styles.min}>
                  <View style={styles.middlecon}>
                    <Text style={styles.content} numberOfLines={2} ellipsizeMode="tail">
                      {item.content}
                    </Text>
                  </View>
                </View>

                {item.Image && (
                  <View style={styles.rightcon}>
                    <Image style={styles.Image} />
                  </View>
                )}
              </View>
            </>
          );
        };

        const styles = StyleSheet.create({
          main: {
            borderBottomWidth: 0.3,
            borderColor: '#b0b4b8',
            paddingBottom: 30,
            flexDirection: 'row',
            justifyContent: 'space-between',
          },

          min: {},

          middlecon: {},

          content: {},

          rightcon: {
            backgroundColor: 'lightblue',
          },

          Image: {
            width: 100,
            height: 30,
            backgroundColor: 'lightgreen',
            
          },
        });

React components and math expressions in .mdx file are not rendering correctly in Next.js application

My custom React components when imported in a .mdx file, are not being rendered at all. The math expressions in the .mdx file either render unformatted or throw parsing errors in spite of following the configuration instructions in the Next.js (https://nextjs.org/docs/advanced-features/using-mdx) and MDX documentation (https://mdxjs.com/guides/math/).

Here are my configurations:

//next.config.js
/** @type {import('next').NextConfig} */

const remarkMath = import('remark-math');
const rehypeKatex = import('rehype-katex');

const withMDX = require('@next/mdx')({
  extension: /.mdx?$/,
  options: {
    remarkPlugins: [remarkMath],
    rehypePlugins: [rehypeKatex],
    // If you use `MDXProvider`, uncomment the following line.
    // providerImportSource: "@mdx-js/react",
  },
})
module.exports = withMDX({
  pageExtensions: ['ts', 'tsx', 'js', 'jsx', 'md', 'mdx'],
  reactStrictMode: true
})


//package.json

  "dependencies": {
    "@mdx-js/loader": "^2.1.1",
    "@next/mdx": "^12.1.5",
    "fs": "^0.0.1-security",
    "gray-matter": "^4.0.3",
    "next": "12.1.5",
    "path": "^0.12.7",
    "react": "18.0.0",
    "react-dom": "18.0.0",
    "recharts": "^2.1.9",
    "rehype-katex": "^6.0.2",
    "remark": "^14.0.2",
    "remark-html": "^15.0.1",
    "remark-math": "^5.1.1"
  },
  "devDependencies": {
    "@types/node": "17.0.25",
    "@types/react": "18.0.5",
    "@types/react-dom": "18.0.1",
    "eslint": "8.13.0",
    "eslint-config-next": "12.1.5",
    "typescript": "4.6.3"
  }

Here is my custom Document component to allow the app to fetch the katex.min.css file:

//_document.tsx
import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
    return (
        <Html>
            <Head>
            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-KiWOvVjnN8qwAZbuQyWDIbfCLFhLXNETzBQjA/92pIowpC0d2O3nppDGQVgwd2nB" crossOrigin="anonymous"/>
            </Head>
            <body>
                <Main />
                <NextScript />
            </body>
        </Html>
    )
}

What is it that I’m not doing correctly?

Having problem connecting JS to my html, getting unexpected token error

I’m trying to run my app (my js file which should run a function to my html file) and all it should do for now is print ‘Hello, World!’ on the browser but I keep getting SyntaxError: Unexpected token ‘<‘ when trying to run my App.js

My HTML file looks like:
1

and my JS files look like:
2
3

my dependencies are:
4

the error I keep getting when trying to run App.js:
5

Cannot find my npm package after installing

I have an npm package that I published and I’m trying to install it in another application that I’m writing.

I have it installed and the files are present and up to date in node_modules, but when I try to import it like so:

import { Message } from 'discord-helper-lib';

I get the following error:

Error [ERR_MODULE_NOT_FOUND]: Cannot find package
‘C:pathtocodenode_modulesdiscord-helper-lib’ imported from
C:pathtocodeapiGameUpdater.js

The package itself has the following package.json:

{
    "name": "discord-helper-lib",
    "version": "2.0.2",
    "description": "Discord Helper Library",
    "type": "module",
    "scripts": {},
    "dependencies": {
        "emoji-regex": "^9.2.2"
    }
}

and the class I’m trying to import is defined as follows:

export default class Message {
    constructor(text, messageReplyDetails) {
           //..
    }
}

Why function slice() sometimes return undefined using regex

So, when I do this

let message = "<@s> has {@s|health} HP";
let score = /({S+})|(<[@a-zA-Z0-9]+>)/g;

let output1 = message.split(score);
console.log(output1);

It return this:
[ '', undefined, '<@s>', ' has ', '{@s|health}', undefined, ' HP' ]

Why does it return some undefined in an array? And how to make sure I didn’t get the undefined on my array?

Javascript to close overlay window in wordpress after scroll to anchor point

When an page scroll event takes place to scroll to an anchor point #down, how can I trigger close of a lightbox overlay?

Using Divi theme in WordPress I have created a page with a plugin called divi overlays. The overlay is a lightbox which can be exited by clicking on either “X” in the corner.

Clicking on book video visit I can trigger scrolling down to the anchor #down but I’m not sure how to use this action to trigger closing the overlay.

https://imgur.com/a/FFGdiio

Any help is much appreciated.