Letter Count- Have the function LetterCountI(str) take the str parameter being passed and return the first word with the greatest number rep letter

For example: “Today, is the greatest day ever!” should return greatest because it has 2 e’s (and 2 t’s) and it comes before ever which also has 2 e’s. If there are no words with repeating letters return -1. Words will be separated by spaces.
Input:”Hello Apple Pie”
Output should be:”Hello”
Do not understand what is wrong with my code, also if you think there is a simpler and shorter way to solve I would love to hear it. Thanks in advance for the help.

  function LetterCountI(str) { 
    let unique=[... new Set(str)]
    if(unique==str){ 
      return -1}
    
    let arr= str.split(" ") 
    
    let array=arr.map(item=>{ 

    let temparr=item.split("")

      return temparr.reduce((acc,curr)=>{ 
    acc[curr]=acc[curr]? acc[curr]+1:1 
    if(acc[curr]>acc.max){ 
      acc.max=acc[curr]}
return acc},{max:1, word:item})}) 
    
    let amount=1
    let largest=""
    
    for(let item of arr){ 
      if( item.max>amount){ 
        amount=item.max 
        largest=item.word
      }
    } 
    
    return largest
    
   }

why aren’t my sorted search results being rendered

I’m creating a simple app that queries an api that returns a list of books when you search by title. I am adding the option to sort the search results.

When a user searches for a title, eg ‘harry potter’, the app stores an array of books in state and renders the results.

When a user THEN (after searching, not before) selects the option to sort by title, my array of books in state is correctly being sorted and updated, but the old unsorted books are the ones shown. Even though my books array is correctly sorted based on console logs, my search results are not.

Notably, if a user selects a search filter before searching, the sorted results render correctly.

Any ideas what might be going wrong?

sandbox

Javascript text changes only on second click [closed]

I have a toggle button which expands and collapses a given text.
Here is the toggle function:

var seeMoreSeeLess = function (questionId, read_more_id) {

    var question = document.getElementById(questionId);
    var read_more_link = document.getElementById(read_more_id);
   
    if (question.classList.contains("opened")) {
      question.classList.remove("opened")
      read_more_link.innerHTML = "...Read more"
    } else {
      question.classList.add("opened")
      read_more_link.innerHTML = "Read less"
    }
}

I’m adding className “opened” to increase the height of container so that whole text is visible. If the className doesn’t contain “opened” keyword, the container shows few lines of text.

Issue: My code is working fine ONLY if I double click. The text doesn’t change from “Read more” to “Read Less” on single click.

Am I missing something here?

Why i am getting undefined my code output [duplicate]

I trying to access value from the input tag but output is showing me null or undefined in console.

<div class="ui-widget">
       <div class="searchbar">
             <input type="text" id="tags" placeholder="Search for a state...">
       </div>
             button type="button" id="add-btn-data" onclick="addstate()">add</button>
</div>
var inputstate = document.getElementById('tags').value;
function addstate(){
    console.log(inputstate);
}

In React, how do I make the tbody of an html table scrollable?

for context I’m using React, Node, Express, Postgres to pull data from a db.

I have an html table in a div that spans across the entire screen. The only way I could succeed in making just the table scrollable I had to add display: block to the header and body sections. The problem was this floated my table to the left so the header and body sections weren’t aligned.

Table in question:

<h1>Inventory</h1>
        <div id="Inventory">
            <table className="table" id="InventoryTable">
                <thead id="InventoryHead">
                    <tr>
                        <th>Material</th>
                        <th>Thickness</th>
                        <th>Width</th>
                        <th>Length</th>
                        <th>Quantity</th>
                        <th>Supplier ID</th>
                    </tr>
                </thead>
                <tbody id="InventoryBody">
                    {inventory.map(inventory => (
                            <tr key={inventory.inventory_id}>
                                <td>{inventory.inventory_material}</td>
                                <td>{inventory.inventory_thickness}</td>
                                <td>{inventory.inventory_width}</td>
                                <td>{inventory.inventory_length}</td>
                                <td>{inventory.inventory_quantity}</td>
                                <td>{inventory.supplier_id}</td>
                            </tr>
                        ))}   
                </tbody>
            </table>
            
        </div>

CSS used:

#Inventory {
  overflow: scroll;
  max-height: 300px;
}

Please let me know if there’s more info I can provide, thanks!

So far I have tried to use display: block to be able to scroll just the tbody. This worked, but it also broke the table structure. As a workaround I applied overflow: scroll to the div instead, but this isn’t ideal because the table header gets scrolled as well.

How can I get a forEach function to render data once instead the number of times the element exists?

I am having an issue where I have a forEach function that grabs 3 elements on my page and tries to render data from an API. The issue is the function is rendering the data 3 times instead of just the once for each element. The function is supposed to filter the information from the API to match the correct element and render its matched data but instead I am getting all the 3 data sets from API rendered on to each element.

I am trying to filter the information from the API by the DOM element name and match that to the name that is being pulled from the API which should be the same.

Hope this all makes sense and someone could help me out.

My code is below which will hopefully explain my predicament:

      fetch(`${window.location.origin}/uk/json/saveditems/getSavedItems.json`)
        .then((response) => response.json())
        .then((data) => {
          const entries = data.data.entries
          // for (let i = 0; i < entries.length; i++) {
          //   console.log(entries[i])
          // }
          savedItemColumn()!.forEach((el) => {
            const prodNameEl = el.firstElementChild as HTMLElement
            const prodName = prodNameEl.innerText
            const parentContainer =
              el.closest(".saveditems-column")
            const apiData = entries.filter((entry) => {
              entry.savedItem.name === prodName
            })
            console.log(apiData)
            parentContainer!.insertAdjacentHTML(
              'beforeend',
              categoryButton(entries)
            )
          })
        })
    }```

Thanks in advance! 
 

How chrome extenstion can save Command Line “monitorEvents” output through devtools_page api?

I send a message to the background page from the devtools page,if eval script has a result,bg page can receive the msg ,but if Command Line like “monitorEvents”,it just ‘undefined’. enter image description here

Is there a way to get all the results?

chrome.devtools.inspectedWindow.eval(
  "inspect(monitorEvents(window,'click'))",
  function(result, isException) { 
log(isException);
backgroundPageConnection.postMessage({
    name: 'init',
data:result,
    tabId: chrome.devtools.inspectedWindow.tabId
});
}
);

Trying to access and manipulate a HTML Collection

Hello everybody,

I am trying to access and manipulate a HTML collection using these methods https://attacomsian.com/blog/javascript-htmlcollection .
However, I am having an issue where I can only access it through dev tools console and not via normal JS.
On the screenshot lines 6 and 7 I am logging the HTML collection and its length, and the result is 0.
But when I do the same in dev tools console I get 7. My script is also deferred.
Any help would be really appreciated, thank you! enter image description here

Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. error

import React from 'react'
import axios from "axios"
import { useEffect } from "react"
import { useState } from "react"

export function Profile (){
    const pathname = window.location.pathname
    const[data,setData] = useState([])
    const [loaded,hasloaded] = useState(false)

  let username = pathname.split("/")[1]

useEffect(()=>{
    axios.post('http://localhost:5000/profile/getProfile', {
        "username":username
       })
       .then((res)=> setData(res.data))
})

  return (
    <div className='Wrapper'>
   
    <img/>

{loaded ? <h2>{data[0].username}</h2>:<h2>Loading</h2>}
  
    <img  />

    </div>
  )
}

axios it taking like 10 seconds to get the response is this normal? when i request on postman it takes like 1 second. also how can i render when i have recieved the data without causing to many rerenders?

Electron: how to open an url in the same window and after the user do some action go back to application in the same window

I have an Electron app that is displayed using BrowserWindow. I want to open an external url in the same window so that the user can log in (in an external website) and after the user logs in it should display the Electron application again instead of the external website that the user used to log in.

I’ve been able to open the external url in the same window by using:

<a href="https://loginsite-example.com" target="_blank" rel="noreferrer">
  site where you have to log in
</a>

However I don’t know how to show the Electron application again after the user successfully logs in into the external website. Also I would like to keep the session from the external website so that I could consume its API inside the electron application.

How to generate QR code from a string and print from jsPDF

I get SignedQRCode from eInvoice portal in encrypted jwt format. I would like to print this in jsPDF, from Angular 12 application.

What I tried but no luck

const signedQRCode = myQRCode;
doc.addImage(signedQRCode, 'JPG', pageWidth - 40, qrImgLocation, 40, 40);

I can able to display in html page with below library but I want to print through jsPDF

npm install angular2-qrcode --save
<qr-code [value]="'https://www.freakyjolly.com/'"></qr-code>

Is there a way to display?

Unsafe call of an `any` typed value. Importing function from a javascript file

I am importing two functions from a javascript file. ES lint errors on one of them claiming its an “unsafe call of an any typed value”. However the other one is fine (despite being more complex).

  type Indices = { source: number; destination: number };

  const handleDragEnd = (event: DragEndEvent) => {

    const indices: Indices = getIndices(event);

    const cols: DefaultColumnType[] = reorderItems(
      indices,
      defaultColumns,
      updateDefaultColumnMutation
    );
...

reorderItems and getIndices are both untyped, from a js file. reorderItems is more complex, however doesn’t receive the ES lint error that getIndices does. Any help on how to get rid of the warning would be much appreciated.

Webpack-dev-server “Cannot GET /”

i’m trying to get my webpack-dev-server to run but i face always the error “Cannot Get /” at the browser.
I know that there are serveral questions with the same error, but none of them helped me, so now i will try my luck 🙂

these are my webpack-config.js configurations:

const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/app.ts',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        test: /.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: ['.ts', '.js']
  }
};

package.json:

{
  "name": "ts",
  "version": "1.0.0",
  "description": "test",
  "main": "app.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "webpack-dev-server",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "clean-webpack-plugin": "^4.0.0",
    "html-loader": "^3.1.0",
    "html-webpack-plugin": "^5.5.0",
    "lite-server": "^2.6.1",
    "ts-loader": "^9.2.8",
    "typescript": "^4.6.2",
    "webpack": "^5.70.0",
    "webpack-cli": "^4.9.2",
    "webpack-dev-server": "^4.7.4"
  },
  "dependencies": {
    "lodash": "^4.17.21"
  }
}

And the script to find the bundle.js from index.html looks like that:

<script type="module" src="dist/bundle.js"></script>

Side note: index.html is not in the dist folder like bundle.js, but i get the same error anyways.

thanks for your help!!

Regards ^^

Javascript take “N” random element from array as good, others as wrong

Javascript listing elements in a array except one random element. I need this code for the random item to respond as a good answer. Remaining elements in the array as bad. Good anaswer end game, bad return to start.

Global:

var randomFrame1 = null

var randomFrame2 = null
var root = this

const answers = [
    this.mc1,
    this.mc2,
    this.mc3,
    this.mc4,
    this.mc5,
    this.mc6,
    this.mc7,
    this.mc8,
    this.mc9,
    this.mc10,
    this.mc11,
    this.mc12,
    this.mc13,
    this.mc14,
    this.mc15,
    this.mc16,
    this.mc17,
    this.mc18,
    this.mc19,
    this.mc20,  
];

 //var randomNum 
 var randomNumArr = []
 
 selected = [];
 
 var randomFrameAdd1 = randomFrame1+=1


 answers.forEach((answer) => {
     answer.addEventListener('mouseover', () => {
         answer.cursor = "pointer";
     })
    answer.addEventListener('mouseleave', () => {
         answer.cursor = "default";
     })
    answers[randomFrame1].addEventListener('click', () => {
        playSound('dobrze')
        console.log('------OK')
        this.play(); 
    })
    answers[!randomFrame1].addEventListener('click', () => {
        playSound('zle')
        console.log('------Zle')
        this.play(); 
    })
    
    


});
/*root['mc'+[randomFrameAdd1]].addEventListener('click', () => {
    playSound('dobrze')
    console.log('------OK')
    this.play(); 
})*/

This is my first attempt at writing code for this. The problem is that I don’t know how to deal with it.