How to achive below result using provided array?

I’m builing notifications component where I want to sort notification by dates and display them.

Can someone give me a hint to achieve that?

How can I do it over a following array ?

enter image description here

Array :

   notificationRows: Array(25)
    0:
    notificationRow:
    fee: "20 TEST"
    id: "1.11.191431"
    info: "[userlink=demo3], send 0.00021 TEST to ,[userlink=demo1]"
    key: "1.11.191431"
    time: "2022-05-17 16:54:21"
    type: "transfer"
    [[Prototype]]: Object
    unread: false
    [[Prototype]]: Object
    1:
    notificationRow:
    fee: "20 TEST"
    id: "1.11.191430"
    info: "[userlink=demo3], send 0.012 TEST to ,[userlink=demo1]"
    key: "1.11.191430"
    time: "2022-05-17 14:52:39"
    type: "transfer"
    [[Prototype]]: Object
    unread: false
    [[Prototype]]: Object
    2:
    notificationRow:
    fee: "20 TEST"
    id: "1.11.191427"
    info: "[userlink=demo3], send 0.0021 TEST to ,[userlink=demo1]"
    key: "1.11.191427"
    time: "2022-05-17 14:34:15"
    type: "transfer"
    [[Prototype]]: Object
    unread: false

My expected result is :

enter image description here

MUIv5 AutoComplete multi select customization

I am trying to use mui Autocomplete multi select component but can’t make it work as per my requirements. I want it to have default selected values which will be passed as a props from Parent component and dropdown options which I will be getting via an API.

Problem 1 :
I am able to render my deafult values in input box which was passed as props but my selected values should not be there in options. Right now I can add duplicate values meaning even though I have few items selected by default in input box but still I could see them in dropdown. I have tried to read the docs it says The value must have reference equality with the option in order to be selected. but can’t understand clearly. Is it because I am using 2 different states(arrays) for value and options?.

Problem 2 (Extra requirement)

In addition to the list of usersOptions that I will get from API to populate the dropdown option, I also need to add an option of All.

  1. Whenever something is already selected then user should not be able to click ALL in dropdown but can select any other values(user).

  2. When input box is empty then only he/she can select ALL from the dropdown but in that case the user shouldn’t be allowed to select any other values(user). All other values in dropdown should be disabled.

Basically the user should be able to select only ALL or Individual user(value).

Link to CodeSanbox(https://codesandbox.io/s/naughty-elbakyan-hi16x5?file=/src/AutoComplete.js:0-1399)

import { useEffect, useState } from "react";

//This is the structure of data for both users & usersOptions
const AutoComplete = ({ users }) => {
const [selectedUsers, setSelectedUsers] = useState(users);

const [usersOptions, setUsersOptions] = useState([]);

 useEffect(() => {
 // fetch("https://x.com/api/getUsers")
 //   .then((response) => response.json())
 //   .then((data) => setUsersOptions(data));
 //let's assume API returned this
 const usersOptions = [
   { id: 1, name: "User 1" },
   { id: 2, name: "User 2" },
   { id: 3, name: "User 3" },
   { id: 4, name: "User 4" },
   { id: 5, name: "User 5" },
   { id: 6, name: "User 6" }
 ];
 const usersOptionsWithAll = [{ id: 0, name: "All" }, ...usersOptions];
 setUsersOptions(usersOptionsWithAll);
 }, []);

 console.log("selectedUsers", selectedUsers);
 console.log("usersOptions", usersOptions);

 return (
 <Autocomplete
   multiple
   id="tags-outlined"
   options={usersOptions}
   getOptionLabel={(option) => option.name}
   filterSelectedOptions
   renderInput={(params) => (
     <TextField {...params} label="" placeholder="" />
   )}
   value={selectedUsers}
   onChange={(event, newValue) => {
     setSelectedUsers(newValue);
   }}
 />
);
};

export default AutoComplete;


[1]: https://i.stack.imgur.com/83V7d.jpg

Need to generate a new string in javascript

I’m trying to solve a question to create a new compressed string. Each character has a count next to it and I was supposed to come with up a new string in alphabetical order followed by the total count of that character within the string.

For eg:

Input: “a10b1a5c1”
Output: “a15b1c1”

Input: “b10a1b5c1”
Output: “a1b15c1”

How I approached this question?

  1. Have an object with key as char and value as count
  2. Convert the object to string
function stringCompression(s) {
const object={}

    for(var i=0; i<s.length-1; i++) {
      if(s[i].match(/[0-9]/)!==null && s[i+1].match(/[a-zA-Z]/) === null) {
        if(object.hasOwnProperty("s[i]")){
          // Add previous and current value
          } else {
          object[s[i-1]]=parseInt(s[i]+s[i+1]) 
          }
    }
  }
return object
}


// output should be a15b1c1
const output= stringCompression("a10b1a5c1");
const final = Object.keys(output).map(key => `${key}${output[key]}`).join("");
console.log(final)

Question:

  1. Can’t think of a way to sort alphabetically
  2. The function I wrote doesn’t handle if the character has a single digit count
  3. Is there any other way I can optimise the solution?

condition to check the value of an input field starts with ${ and ends with } in javascript

I have an input field which get the values as in the format
value= ${data1}, ${data2}, ${data3}
I have to write a validation in js to check if the value contains each element starting with ‘${‘ and ends with ‘}’.

Suppose if we have value = $data} or {data} or data or ${data or ${data}, $data}. These all should fail.
Could you please help on this?

on click, Stop a button from returning empty string and give an alert message using javascript

When I click on the Add Note Button without entering any text, I do not want the local storage to add an empty string, instead I want an alert message to pop up saying “enter a text”. I tried a few ways trying to place alert function at different points, but an ERROR is displayed saying “properties of null can’t be read”. Please suggest some code.
Thank You.
[1]: https://i.stack.imgur.c

 console.log("Add Notes");
 showNotes();
 
// If user adds a note, add it to the localStorage
let btnBag = document.getElementById("addBtn");
btnBag.addEventListener("click", function(e) {
  let txtBag = document.getElementById("addTxt");
  let notesBag = localStorage.getItem("notes");
  if (notesBag == null) {
    notesBag = [];
  } else {
    notesBag = JSON.parse(notesBag);
  }
  notesBag.push(txtBag.value);
  localStorage.setItem("notes", JSON.stringify(notesBag));
  txtBag.value = "";
  // showAlert();
  showNotes();
});
 
//Function to display elements located in localStorage
function showNotes(){
  // place the notes array in an element called notesBag
let notesBag = localStorage.getItem("notes");
  if (notesBag == null) {
    objBag = [];
  } else {
    objBag = JSON.parse(notesBag);
  } 
  // create a blank string named html
  let html = '';
  // For the notesBag(which is parsed and placed into the objBag element) create forEach loop so that each notes stored in array is shown seperateley
  objBag.forEach(function (element,index) {
    html +=`
    <div id="notes" class=" row container-fluid">
            <div class="noteCard mx-2 my-2 card" style="width: 18rem;">
                <div class="card-body">
                    <h5 class="card-title">Note ${index+1}</h5>
                    <p class="card-text">${element}</p>
                    <button id = "${index} onclick = "deleteNote(this.id)" class="btn btn-primary">Delete Note</button>
                </div>
            </div>
        </div> `;
  
    });
    let notesElem = document.getElementById("notes");
    
    if(objBag.length != 0){
      notesElem.innerHTML = html;
    } else { 
      notesElem.innerHTML = `Add Something for displaying the note`;
        }
    };
  

  //Delete a note





/* // Function to delete a note
function deleteNote(index) {


  let notes = localStorage.getItem("notes");
  if (notes == null) {
    notesObj = [];
  } else {
    notesObj = JSON.parse(notes);
  }

  notesObj.splice(index, 1);
  localStorage.setItem("notes", JSON.stringify(notesObj));
  showNotes();
} */


// let search = document.getElementById('searchTxt');
// search.addEventListener("input", function(){

//     let inputVal = search.value.toLowerCase();
//     // console.log('Input event fired!', inputVal);
//     let noteCards = document.getElementsByClassName('noteCard');
//     Array.from(noteCards).forEach(function(element){
//         let cardTxt = element.getElementsByTagName("p")[0].innerText;
//         if(cardTxt.includes(inputVal)){
//             element.style.display = "block";
//         }
//         else{
//             element.style.display = "none";
//         }
//         // console.log(cardTxt);
//     })
// })


/*Further Features:
1. Add Title
2. Mark a note as Important
3. Separate notes by user
4. Sync and host to web server 
*/  
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Practice code</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <style>
        .navbar-brand {
            color: red;
        }
    </style>
</head>

<body>
    <nav class="navbar navbar-expand-lg  bg-dark ">
        <a class="navbar-brand" href="#">Multiple Notes</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                    <a href="#">Home <span class="sr-only">(current)</span></a>

                </li>
            </ul>
            <form class="form-inline my-2 my-lg-0">
                <input class="form-control mr-sm-2" id="searchTxt" type="search" placeholder="Search"
                    aria-label="Search">
                <button class="btn btn-outline-success  my-2 my-sm-0" type="submit">Search
                </button>
            </form>
        </div>
    </nav>
    <div class="container my-3">
        <h1>Take Notes Here</h1>
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">Add Note</h5>
                <div class="form-group">
                    <textarea class="form-control" id="addTxt" rows="3"></textarea>
                </div>
                <button class="btn btn-primary" id="addBtn" onsubmit="showAlert()">Add Note</button>
            </div>
        </div>
        <hr>
        <h1>Your Notes</h1>
        <hr>
        <div id="notes" class=" row container-fluid">
            <!-- <div class="noteCard mx-2 my-2 card" style="width: 18rem;">
                <div class="card-body">
                    <h5 class="card-title">First Note</h5>
                    <p class="card-text"></p>
                    <a href="#" class="btn btn-primary">Delete</a>
                </div>
            </div> -->
        </div>
    </div>
    </div>

</body>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
    crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
    integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
    crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
    integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
    crossorigin="anonymous"></script>

<script src="harry js files/practice.js"></script>

</html>

om/ZKITG.png

What is the correct syntax of JavaScript Factory Function? JavaScript Factory Function Syntax confusion

Both function getMyCar1 & getMyCar2 has same result but which one is the correct way of doing?

getMycar2: Why value have to use instead of key? key:value (carBrand:brand).

function selectCar(brand, model, color){
    return{
        carBrand: brand,
        carModel: model,
        carColor: color, 

        getMyCar1: function(){
            return this.carBrand + " " + this.carModel + " " + this.carColor;  
         //It is said that no need this key word with factory function 
         //but without this key word not working, why?

        },

        getMyCar2: function(){ 
           return brand + " " + model + " " + color;  
           //NotWorking: return carBrand + carModel + carColor
        }
    };
}

let bmw = selectCar("bmw", "X6", "White");
console.log("My Car Model is: " + bmw.getMyCar1());

let audi = selectCar("Audi", "A8", "Red");
console.log("My Car Model is: " + audi.getMyCar2());

Toggle between useState using Switch from MUI

trying to build my own Dark Mode for a specific component on my create-react-app site and using MUI. I have the Switch working to change the state on toggle but can’t seem to find how to toggle it back and forth. Basically want to turn page dark on toggle and turn back to light on same toggle button. Suggestions please.

import React from 'react'
import Switch from '@mui/material/Switch';


const DarkMode = () => {
    const [color, setColor] = React.useState(false)
  return (
    <div style={{ backgroundColor: color ? '#2c2d30' : '#ffffff' }}>
        <Switch onChange={setColor} />
        <h1 style={{ color: color ? '#ffffff' : '#000000' }}>Hello welcome to my site</h1>
    </div>
  )
}

export default DarkMode

How to read the ref code from URL in react js

I want to get the ref code from the URL, http://localhost:3000/?ref=2926

I try with const session = ${window.location.href}; it gets the full current URL and tries to use split() the pathname but it didn’t work, how to get only the ref code from the URL.

How to hide all elements with a specific class name using JS in Android WebView?

I want to hide all elements with the specific class mobileBTN in my Andriod WebView mobile app with Javascript. I tried adding some JavaScript code to hide the elements but it doesn’t work.

Here is my Andriod WebView App code:

package com.app.pvm;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = findViewById(R.id.MyWebView);

        webView.setWebChromeClient(new MyChromeClient());
        webView.setWebViewClient(new BrowserClient());

        WebSettings settings = webView.getSettings();
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(true);

        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);

        webView.loadUrl("https://test.app");
        
        webView.loadUrl("javascript:"
                + "var myClasses = document.querySelectorAll('.mobileBTN'),i = 0,l = myClasses.length;"
                + "for (i; i < l; i++) {myClasses[i].style.display = 'none';}"
                + "};");
    }
}

XML Code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <WebView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/MyWebView"/>
</LinearLayout>

BrowserClient Class code:

package com.app.pvm;

import android.graphics.Bitmap;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

class BrowserClient extends WebViewClient {

    public BrowserClient(){

    }

    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
    }


}

Note: I’m using Andriod Studio for the WebView App.

Why my state is not getting set inside class based component and it should work but it is not neither i am getting error

The issue i am facing is i am not able to set my state in the class based component i don’t know whats wrong with it i have created a very small project before this so that i can practice the state manipulation and i am doing the same way as test project working please help

import React, { Component } from 'react';
import { Header } from './components';
import { ProductListing, ProductDetail, Cart } from './Screens';

import {
    Routes,
    Route,
    Navigate
} from "react-router-dom";

export class App extends Component {
    constructor(){
        super();
        this.state = {
            products: [],
            cart: []
        }
    }

    async componentDidMount() {
        const query = `
    query{
      categories {
          name
          products {
            id,
            name,
            inStock,
            gallery,
            category
          }
        }
  }
    `;
        fetch("http://localhost:4000", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json",
            },
            body: JSON.stringify({
                query
            })
        }).then(response => {
            return response.json();
        }).then(data => {
            this.setState({
                products: data.data.categories,
            })
            console.log("The data i am getting is", data.data.categories);
            
        })
        console.log("The prodcuts are", this.state.products)
    }
    render() {
        return (
            <>
                <Header />
                <Routes>
                    <Route path="/" element={<Navigate replace to="/all" />} />
                    <Route path="/:category" element={<ProductListing products={this.state.products} />} />
                    <Route path="/product" element={<ProductDetail />} />
                    <Route path="/cart" element={<Cart />} />
                </Routes>
            </>
        )
    }
}

export default App

I don’t understand why this piece of code is not working it is supposed to set the data and send it to the component but is not doing that actually and neither giving error

this.setState({
             products: data.data.categories,
         })

the below piece of code

console.log("The data i am getting is", data.data.categories);

enter image description here

Is it possible to fire mouse events without mouse moves in safari?

I’m trying to put mouse enter/mouse-leave events on moving elements. There is a problem in handling the hover event with CSS, so I’m trying to process it with JS. This works fine in chrome but not working in safari. How to make mouseenter/mouseleave work properly when the mouse is stopped?

CSS

.big-box {
    position: relative;
    width: 500px;
    height: 100px;
    background: #ee9;
}
.hit-box {
    position: absolute;
    top: 0;
    left: 0;
    width: 100px;
    height: 100px;
    background: #e99;
}

HTML

<div class="big-box">
    <div class="hit-box">hit-box</div>
</div>

JavaScript

const hitbox = document.querySelector('.hit-box');
var position = 5;
hitbox.style.left = 0;

hitbox.addEventListener('mouseenter', function() {
    console.log('enter');
});
hitbox.addEventListener('mouseleave', function() {
    console.log('leave');
});

setInterval(function() {
    if(parseInt(hitbox.style.left) + position > 400) {
        position = -5;
    } else if(parseInt(hitbox.style.left) + position < 0) {
        position= 5;
    }
    hitbox.style.left = parseInt(hitbox.style.left) + position + 'px';
},20)