Text input does not change slider value on first attempt

I am making a password generator with a text input and slider value that are tied together, however when I type in a value the first time it will not update. When I try again it works, as well as working subsequent times. The slider value always updates. I don’t know what is wrong with the code to make it perform like this though, still fairly new to JS.

//html

<div class="slider">
    <input type="text" id="slider-input" value="" onchange="setSlider(this)">
    <input type="range" min="1" max="64" value="1" id="slider" oninput="myFunction(this)">
</div>

//JS

const sliderInput = document.getElementById("slider-input");
const slider = document.getElementById("slider");

let passLength = "";
function myFunction() {
    slider.oninput = function() {
    sliderInput.value = this.value;
    passLength = this.value;
    }
}

function setSlider() {
    sliderInput.addEventListener("change", function() {
    slider.value = this.value; 
    passLength = this.value;
    })
}

Issue: React contact form increments every API call n +1 times after every submission and doesn’t submit after first click

I’m building out a contact form for my portfolio web app using Firebase Firestore as the database for the form input data.

1st issue: When I click the submit button it doesn’t execute the API call to write the data to the database on the first try, but it works on the second submit button click.

2nd issue: Every form submission after the first initial submit keeps incrementing the API call by n + 1.

(e.g. the second time I try to submit the form the input data records twice in the data base. The third time I try to submit the form, the data records three times in the data base for the same input… and so on.)

I am fairly new to React and JS so thanks in advance!

import React, { useState } from "react";
import './contact.css';
import { initializeApp } from "firebase/app";
import {
getFirestore, collection, getDocs, addDoc
} from 'firebase/firestore';


const firebaseConfig = {
apiKey: "xxxxxx",
authDomain: "xxxxxx",
projectId: "xxxxxx",
storageBucket: "xxxxxx",
messagingSenderId: "xxxxxx",
appId: "xxxxxx"
};

// Initializing the Firebase Firestore database
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const colRef = collection(db, 'contacts')

// Read the existing documents from the database and console.log them
const findDocs = () => {
getDocs(colRef)
  .then((snapshot) => {
    let contacts = []
    snapshot.docs.forEach((doc) => {
      contacts.push({ ...doc.data(), id: doc.id })
    })
    console.log(contacts)
  })
  .catch(err => {
    console.log(err.message)
  })
}

// Handling the contact form submission 
const handleSubmit = (e) => {
findDocs();
e.preventDefault();

const addContactForm = document.querySelector('.add');

addContactForm.addEventListener('submit', async (e) => {
  e.preventDefault();
  await addDoc(colRef, {
    name: addContactForm.name.value,
    email: addContactForm.email.value,
    message: addContactForm.message.value,
  })
    .then( () => {
      addContactForm.reset();
      console.log('Form submitted');
    })
})
}

function Contact() {

return (
    <form onSubmit={handleSubmit} className="add" >
      <h1 className="contact-form-h1" >Contact Me</h1>
      <h5 className="replying-shortly">I will be replying shortly!</h5>

      <label className="form-headings" htmlFor="name">Name</label>
      <input type="text" name='name' placeholder="Name" required />

      <label className="form-headings" >Email</label>
      <input placeholder="Email" type="text" name='email' required />

      <label className="form-headings" >Message</label>
      <textarea placeholder="Message" type="text"
        name='message' required>
      </textarea>

      <button type="submit">Submit</button>
    </form>
);
};

export default Contact;

Complex method chaining

For context, I’m thinking about this type of method chaining, in which the final method called returns a promise. My question is different from this one, however.

I’m truly stumped with this, so bear with me on my lack of reproducible examples. I’m not even too sure where to begin with this. It’s also not a homework question.

Consider the function foo on the class Bar, which takes in a few parameters. foo is asynchronous and returns a promise. baz is totally optional, and can be chained onto foo (foo(param).baz(someOtherParam)), which will affect the way foo is eventually run. What’s important to note here is that foo will return without the chained baz being called, but if baz IS called, it will be the one who returns the promise (not foo).

My explanation is probably confusing, so here’s a visual example:

// The promise is returned by the .where() 
const data = await User.where({ age: { $gte: 21 } })

// The .gte() function affects the execution. The promise is returned from .gte()
const data = await User.where('age').gte(21)

// .gte() doesn't return the promise anymore. The second chained .where() does.
// But also we can just continue chaining onto that pretty much endlessly if we want to.
const data = await User.where('age').gte(21).where('name', /^b/i)

I understand how to method chain with synchronous functions just fine – just return an object with some methods on it and you’re pretty much good to go. What has me stumped is this implementation, which you can see a lot in libraries.

How to check update and insert while using bulkCreate in node.js

I am using node.js to upload an excel file into the database, in my service i am using bulkCreate to upload the data into the mysql db.Let me post the table structure

  table name : customer_details
  columns:
  customer_org_id INT,
  customer_name VARCHAR,
  customer_type char,
  active boolean,
  customer_slot VARCHAR,
  service_start_time DATE,
  service_end_time DATE

I have one additional requirement that is, while i will upload the excel and try to push into the db then it must check in the database that customer_org_id &customer_name exists in the database or not.If the combination exists then the existing record will be updated and active column will be false.And a new row will be inserted with customer_org_id & customer_name and the active will be set to true.I am able to do the individual operations like create , update ,delete etc but i don’t understand where to put these operations together while doing a bulkCreate. I am posting my code

const upload = async(req,res) => {
 try{
      if(req.file == undefined){
        return res.status(400).send("Please upload an excel file");
     }
  let path=
    __basedir + "/resources/static/assets/uploads/" + req.file.filename;

  readXlsxFile(path).then((rows)=>{
      rows.shift();
      let custdetail = [];
      
      row.forEach((row)=>{
        let custdetails ={
          customer_org_id: row[0],
          customer_name :row[1],
          customer_type :row[2],
          active :row[3],
          customer_slot: row[4],                           
        }; 
       custdetails.push(custdetail);
       });

     CustomerDetails.bulkCreate(custdetails)
       .then(()=>{
       res.status(200).send({
       message: "Uploaded the file successfully :" + req.file.originalname,
       });
       })
       .catch((error) =>{
        res.status(500).send({
        message : "Fail to import data into DB",
        error : error.message,
        });
      });
     });
    }catch(error){
    console.log(error);
    res.status(500).send({
    message : "Could not upload the file :" +req.file.originalname,
   });
   }
  }

Can anyone let me know how i can do the operations before adding data to the Db ? I am new to node js

Yup lazy validation not working when return value is not static

Link to CodeSandbox. Using my validation schema below, I would like to validate tenant only when it contains a value and renterType === RenterType.BUSINESS. Since I depend on a live value I figured I would use lazy. But for some reason the return value is not evaluated properly, when I explicitly return true or false it does seem to validate. How can I achieve the wanted behavious?

import { object, string, lazy } from "yup";
import { useFormik } from "formik";

type FormValues = {
  renterType: RenterType;
  tenant?: string;
};

enum RenterType {
  BUSINESS = "business"
}

const validationSchema = object().shape({
  renterType: string().oneOf(Object.values(RenterType)).required(),
  tenant: lazy((value) =>
    string()
      .nullable()
      .when(["renterType", "tenant"], {
        is: (renterType: RenterType, tenant: string) => {
          const bool = renterType === RenterType.BUSINESS && value?.length > 0;
          console.log({
            renterType,
            tenant,
            value,
            bool
          });
          return bool;
        },
        then: string().required()
      })
      .label("tenant")
  )
});

export default function App() {
  const form = useFormik<FormValues>({
    validationSchema,
    initialValues: {
      renterType: RenterType.BUSINESS
    },
    onSubmit: () => {}
  });

  return (
    <div className="App">
      <form onSubmit={form.handleSubmit}>
        <input
          name="tenant"
          onChange={form.handleChange}
          value={form.values.tenant}
        />
        {form.errors.tenant && <p>{form.errors.tenant}</p>}
        <button type="submit">submit</button>
      </form>
    </div>
  );
}

Create a new .html file with text based upon the information one user enters in set HTML form

Is it possible to make a HTML form (which will have a Full Name, Location, Phone Number input fields for example) that will once the user enters his custom information inside of the form create a new .html file with that set information that user entered on the form.

To clarify, if the user enters:

Full Name: Vlado
Location: Vlado Town
Phone Number: 29378173788732784724 (just a random number)

Then the .html page will have “Full Name: Vlado”, “Location: Vlado Town”, and you get the point. And if the user enters something else, the new .html file will have that other information instead.

I was wondering is this possible without using databases, PhP, or something similar, but rather JavaScript for example.

My idea was to make an empty .html file with all the required text, then make another .html file with the form, and in the JavaScript set a script so every time a user hits the “Submit” button on the form, the empty .html file will duplicate and instead of the default information it will get filled with the user’s information. I’m just not sure how could I execute this properly?

Maybe it could be achieved using arrays as well? But I’m not really sure.

I’ve checked this link, but it features PhP (which I would like to avoid if possible):

Submit button to create HTML file with text entered

Terms and Conditions modal read-detection – Plain Javascript (No libraries)

I’m trying to figure out a way to create a scrollable modal that detects when the reader has scrolled to the bottom before enabling the ‘Agree’ button. This is for a Terms and Conditions type of box. I am also trying to create this with nothing more than plain html, css, and javascript. This is what I have so far.

HTML


<body>

    <h2>Modal Example</h2>

    <!-- Trigger/Open The Modal -->
    <!-- <a href=""> -->
        <input 
            type="checkbox"
            id="agree-checkbox">
        </>
        <p>
            I HAVE READ THE <span><a href="">PRIVACY POLICY</a></span> AND AGREE TO THE <span><a href="">TERMS AND CONDITIONS</a></span> OF THIS AGREEMENT.
        </p>
    <!-- </a> -->
    
    
    <!-- The Modal -->
    <div id="terms-modal" class="modal">

        <div class="modal-inner-container">
            <div class="modal-header">
                <span class="close">&times;</span>
            </div>

            <!-- Modal content -->
            <div class="modal-content">
                

                <!-- <p>Some text in the Modal..</p> -->
                <div id="agreement" class="termsImages">
                    <p>
                        Lorem ipsum dolor sit amet consectetur adipisicing elit. Repudiandae reprehenderit est, hic esse, numquam omnis autem exercitationem eum a nobis perspiciatis et labore voluptatibus accusamus molestias eveniet laboriosam amet cumque ut, fuga soluta atque porro eaque voluptatem? Doloremque, culpa modi. Corrupti optio similique excepturi inventore architecto ipsum, officiis explicabo sunt ducimus, iusto dolorum animi eius pariatur fuga consectetur rerum? Ratione, amet. Explicabo culpa accusamus consectetur esse odio quis, unde officiis quidem veniam, doloremque sed modi error tenetur eligendi quisquam molestiae, ut dicta suscipit nisi officia necessitatibus voluptatem ex delectus. Praesentium tenetur consequuntur repellendus voluptatum, dolorem adipisci. Voluptate ab repellendus eum nobis alias quae corporis odit quasi unde, aut pariatur quod! Laboriosam qui quisquam minima quia, eum perspiciatis odio non ullam ipsum culpa quae iste voluptatum velit aspernatur? Nisi vitae dolor fuga dignissimos facere culpa voluptate, delectus ipsam iste laboriosam at iure. Quod porro perferendis modi laboriosam, error expedita explicabo similique et ex, facilis dignissimos natus, tenetur cupiditate iure tempora debitis aspernatur repudiandae sequi voluptatem eos blanditiis! Veritatis pariatur hic illum. Nemo laboriosam aliquam reiciendis! Voluptas sequi modi nisi veniam error vel aperiam a ab ipsam, nam porro rerum laudantium totam corporis suscipit maiores quam nihil temporibus asperiores, ex consequuntur doloremque! Illo nisi tenetur minima consectetur ad iste non molestias fugit, laborum molestiae delectus fugiat saepe quos dolorum? Magni nobis consequatur ut maiores adipisci magnam rem ex odit nesciunt ullam temporibus rerum quis, nostrum distinctio quisquam facilis quia ducimus necessitatibus impedit earum deleniti. Mollitia, tempore minima? Atque molestiae perspiciatis velit dolore eius? Nisi id aperiam magnam consequatur eum distinctio, architecto aliquid temporibus. Natus accusantium magni fugit aliquid, libero ratione. Modi maiores asperiores, consectetur dignissimos impedit eaque similique culpa quo obcaecati sequi rerum possimus assumenda! Modi nesciunt alias quisquam quas! Quas, maiores. Molestias tenetur nihil, ducimus nam a possimus fugit minima fugiat assumenda dolor molestiae soluta delectus veritatis laborum laudantium quia quae magnam porro saepe quibusdam doloremque. Dignissimos quaerat laborum possimus quis nisi at, sequi delectus, quasi inventore tempore facilis modi repudiandae? Aperiam dolores quos inventore eveniet mollitia est ipsa. Nihil repellat molestiae possimus qui itaque! Cum id recusandae error et dolor beatae iure quidem dolorem ratione, eveniet, consequuntur laborum veritatis. Sapiente quis nostrum possimus illo nihil quisquam consequuntur. Commodi quidem nisi rem porro impedit at, praesentium qui non fugiat aspernatur illo reiciendis et quos soluta atque similique aut? Dolore illum quas obcaecati laboriosam, eos tempora delectus ex rerum iure, temporibus soluta voluptates. Neque recusandae, aspernatur inventore voluptatibus sint quae? Quibusdam repellendus deserunt nobis illo adipisci iste. Sed explicabo dolore accusantium, inventore repellat ratione praesentium minus magni doloremque, itaque ab sunt error, at ut consectetur repudiandae ullam ea repellendus distinctio? Illum modi similique rerum tenetur odit ad quae, vitae architecto repellendus illo harum iste quas iusto eveniet molestiae reprehenderit ab nisi quasi ullam. Aliquid enim vero hic ipsam natus consequuntur, at repellat ipsa inventore, sequi veritatis eveniet deserunt illum ut? Error a autem sint consequatur, nulla totam quisquam. Dicta repellendus iste corporis ut? Iusto aperiam aut placeat recusandae similique quis perspiciatis fugit molestiae sapiente consectetur voluptates, quia quae tempora error obcaecati eum perferendis exercitationem ipsam delectus! Saepe earum, alias hic dignissimos deleniti doloribus, minus architecto aliquam odio explicabo vitae ab, blanditiis numquam. Itaque nihil deleniti omnis nobis, vitae odit quam nam excepturi neque officiis iste ducimus quidem tenetur recusandae voluptatem exercitationem, iure sequi sed eum repudiandae fugiat similique? Rem nostrum quidem in quia magnam necessitatibus placeat magni voluptate, dolorum quos adipisci molestiae quibusdam tempora sed, aperiam illum odio excepturi. Voluptate nostrum natus, fugit perspiciatis tempora cupiditate officia alias eos, ducimus ad dolore autem excepturi laborum! Distinctio ad aliquid quibusdam odio nemo, itaque, totam inventore velit corporis illo, facere maxime consectetur fugit consequuntur necessitatibus quia. Debitis adipisci recusandae dicta illo quisquam, tempora voluptas id odit et commodi ab, excepturi iure velit explicabo libero aliquid asperiores officiis vitae aperiam eius? Accusantium sint a labore, pariatur dolores, veniam ipsa quae ab blanditiis consequuntur tempore optio vel aperiam sunt! Dolorem eius adipisci magni ab corrupti, dolor modi recusandae qui ut nam quasi minima ea voluptas ullam corporis blanditiis commodi iure voluptates obcaecati, ducimus velit explicabo? Laborum sit temporibus magni illum qui assumenda porro inventore totam suscipit vero esse perferendis tenetur voluptates eligendi ratione, tempora maiores ex alias sequi impedit amet error. Voluptate, nobis labore, maxime eius repudiandae iusto culpa quidem nisi quo, dicta consectetur sint! Et officiis itaque deleniti qui delectus molestiae, doloribus, cumque dolores fugiat inventore quisquam mollitia similique consequuntur sapiente. Nihil vero quod, fugit rerum consequuntur ipsam magnam quibusdam blanditiis amet aut iusto corporis qui repellendus odit reiciendis maxime et sit dolore nam. Eligendi repellendus, at modi deserunt accusamus voluptate expedita eos culpa adipisci, voluptatum sed veniam quaerat quod quibusdam distinctio natus animi odio maxime facere repudiandae! Minus dolore eum illum numquam! Labore velit enim amet at doloribus esse magnam natus eaque provident mollitia!
                    </p>

                </div> 

                
            </div>

            <div class="modal-footer">
                <p class="instructions">Please read through to the end of the Agreement to enable the AGREE button.</p>
                <button type="button" id="agreeBtn" class="agree-Btn" data-dismiss="modal" aria-hidden="true">AGREE</button>
            </div>            

        </div>
    
    </div>



    <script src="./assets/script.js"></script>
</body>

CSS

body {font-family: Arial, Helvetica, sans-serif;}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    padding-bottom: 100px;
    left: 0; 
    top: 0;
    scroll-behavior: smooth;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    /* overflow: auto; Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
    overflow: hidden;
    border-radius: 5px;

}

.modal-header {
    display: flex;
    justify-content: flex-end;
    width: 100%;
    padding-right: 5%;
}

.modal-inner-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    /* align-self: center; */
    /* padding-bottom: 10%; */
    width: 70%;
    background-color: #fefefe;
    border: 1px solid #888;
    /* margin-bottom: 20%; */
    margin-right: 10%;
    margin-left: 10%;
    height: 450px;
    /* padding: 20px; */
    border-radius: 5px;

}

#agreement {
    height: 350px;
    margin-bottom: 5%;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
}

/* Modal Content */
.modal-content {
    display: flex;
    flex-direction: column;
    /* justify-content: center; */
    align-items: center;
    background-color: #fefefe;
    margin: auto;
    /* padding: 20px; */
    border: 1px solid rgb(179, 179, 179);
    border-radius: 5px;
    width: 97%;
    /* margin-bottom: 20%; */
    overflow-y: scroll;
}

.modal-footer {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

JS

var termsModal = document.getElementById("terms-modal");

// Get the button that opens the modal
var agreeCheckbox = document.getElementById("agree-checkbox");

// Get the <span> element that closes the modal
var closeModal = document.getElementsByClassName("close")[0];

var modalContent = document.getElementsByClassName("modal-content");

var agreeButton = document.getElementById("agreeBtn");

var agreementContainer = document.getElementById("agreement");


// Enables agree button when user scrolls all the way down
// modalContent.scroll(function() {
//     var disable = (((agreementContainer.height())) >= (modalContent.scrollTop() + modalContent.height() + 1));
//     agreeButton.disabled = disable;
// })


// When user clicks agree button in modal, keeps agree checkbox checked
agreeButton.onclick = function() {
    agreeCheckbox.checked = true;
    termsModal.style.display = "none";
}

// When the user clicks the button, open the modal 
agreeCheckbox.onclick = function() {

    if (agreeCheckbox.checked === true) {
        termsModal.style.display = "block";
    } else {
        agreeCheckbox.checked === false;
    }
}

// When the user clicks on <span> (x), close the modal
closeModal.onclick = function() {
    termsModal.style.display = "none";
    agreeCheckbox.checked = false;
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        termsModal.style.display = "none";
        agreeCheckbox.checked = false;
    }
}

It’s not currently working. Any help is appreciated!

Material UI checkbox toggle value based off input from object

I have an unchecked checkbox. I am trying to change the value of it based off of data from an object. The object is from an SQL select boolean column ‘T’ or ‘F’. If the value is ‘T’ then the box would be checked vise versa. I tried using a useState() that viewed the value but that didn’t work.

  const [checkBoxState, setCheckBoxState] = React.useState(false);
  //check to see if values are 't' or 'f' to change them to vaiable formats
  function handleCheckState(databaseCondition) {
    if (databaseCondition == "T") {
      setCheckBoxState = true;
    }
    console.log(checkBoxState);
    return checkBoxState;
  }

This is the useState() I tried using.

<Checkbox checked={handleCheckState(data["validcycle"])} />

Here is the checkbox I want to toggle on/off based off that sql column.

How it is to Mouse events to Touch Events for mobile using div class?

basically I want the mouseevents to work on mobile through the use of touchevents.

On this :

https://codepen.io/benstl/pen/LYQjKvN

I’m really lost there… I think i need to put each
document.addEventListener(“touchstart” /”touchmove”/”touchend”)

document.addEventListener('mouseup', grabOff);

document.addEventListener(‘mousemove’, handleMouseMove);

But how deal with the console.log ?

Thank you for your help, i really appreciate, all the best

check if a map inside array has multiple keys and values in Javascript

I have a following array of maps

let input = [
            {"name":"apple", "type":"fruit", "color": "red"},
            {"name":"apple", "type":"fruit", "color": "green"},
            {"name":"tomato", "type":"fruit", "color": "red", "taste":"sweet"}, 
            {"name":"tomato", "type":"fruit", "color": "green", "taste":"sour"}
            ]; 

How do I check if there are two elements in this array – one containing red apples and green tomatoes?

I tried this:

console.log (
        input.some(
          (subMap) => subMap.name == "tomato" && subMap.color == "green")
        && 
        input.some(
          (subMap) => subMap.name == "apple" && subMap.color == "red"));

For the above array, this returns true.

Looking for a more concise way of checking this.

Something like

input =[      
       {"name":"apple", "type":"fruit", "color": "red"},
       {"name":"apple", "type":"fruit", "color": "green"},
       {"name":"tomato", "type":"fruit", "color": "red", "taste":"sweet"}, 
       {"name":"tomato", "type":"fruit", "color": "green", "taste":"sour"}
       ]; 
subArray = [{"name" : "apple", "color":"red"} , {"name":"tomato", "color" : "green"}]

//This function should return true 

(input.hasElementsMatching(subArray)) => true

Thanks in advance

Angular Bootstrap 5 not working when add @types/bootstrap

I have a problem with bootstrap and its @types, when I uninstall the @types it works correctly again

What happens is that an error is raised when I add @types/bootstrap, which I wanted to add to make use of the Toast and Modal that bootstrap has dynamically

I have a “dropdown” that does not cause any errors except when it is inside a “navbar” as a bootstrap class, it does not display the “dropdown-menu”

In the “angular.json” I have added the route

"scripts": [
    "node_modules/bootstrap/dist/js/bootstrap.min.js"
]

In the component for header I have the following navbar

enter image description here

<nav class="navbar navbar-expand-lg navbar-light bg-light" aria-label="Ninth navbar example">
    <div class="container-xl">
        <a [routerLink]="['/blog/home']" class="navbar-brand" title="Home Page">
            <img loading="lazy" src="assets/icon.ico" width="30" height="30" class="d-inline-block align-top" alt="Home Page"> Cétr!co.Blog
        </a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#toogleMenu" aria-controls="toogleMenu" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="toogleMenu">
            <ul class="navbar-nav me-auto mb-2 mb-lg-0 d-flex flex-column flex-lg-row">
                <li class="nav-item d-flex justify-content-center">
                    <a [routerLink]="['/blog/home']" routerLinkActive="active" class="nav-link">Inicio</a>
                </li>
                <li class="nav-item d-flex justify-content-center">
                    <a [routerLink]="['/blog/anthology']" routerLinkActive="active" class="nav-link">Antología</a>
                </li>
                <li class="nav-item d-flex justify-content-center">
                    <a [routerLink]="['/blog/contact']" routerLinkActive="active" class="nav-link">Contact</a>
                </li>
                <li class="nav-item d-flex justify-content-center">
                    <a [routerLink]="['/blog/search']" routerLinkActive="active" class="nav-link">
                        Buscar &nbsp; <i class="fas fa-search"></i>
                    </a>
                </li>
            </ul>
            <ng-container *ngIf="userLogged() else userMenu">
                <div class="btn-group d-flex flex-row justify-content-center" role="group">
                    <button [routerLink]="['/auth/login']" routerLinkActive="active" type="button" class="btn btn-outline-secondary" title="Ingresa como usuario">
                        Ingresar
                    </button>
                    <button [routerLink]="['/auth/signin']" routerLinkActive="active" type="button" class="btn btn-outline-success" title="Registrate como usuario">
                        Registrarse
                    </button>
                </div>
            </ng-container>

Where the important thing is here, I want to use a dropdown to display a menu of options

            <ng-template #userMenu>
                <div class="btn-group d-flex flex-column flex-lg-row justify-content-center" role="group">
                    <button type="button" class="btn btn-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                        Usuario: {{_user.getNickname}}
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li>
                            <a [routerLink]="['/user', _user.getNickname]" routerLinkActive="active" class="dropdown-item btn d-flex justify-content-between align-items-center">
                                Perfil
                                <i class="far fa-user-circle"></i>
                            </a>
                        </li>
                        <li>
                            <a [routerLink]="['/user/bookmarkeds']" routerLinkActive="active" class="dropdown-item btn d-flex justify-content-between align-items-center">
                                Guardados
                                <i class="fa fa-bookmark" aria-hidden="true"></i>
                            </a>
                        </li>
                        <li *ngIf="_user.hasRole(['EDIT', 'GRANT', 'ADMIN'])">
                            <a [routerLink]="['/dashboard/post']" routerLinkActive="active" class="dropdown-item btn d-flex justify-content-between align-items-center">
                                Nuevo Post
                                <i class="far fa-file"></i>
                            </a>
                        </li>
                        <li *ngIf="_user.hasRole(['GRANT', 'ADMIN'])">
                            <a [routerLink]="['/dashboard']" routerLinkActive="active" class="dropdown-item btn d-flex justify-content-between align-items-center">
                                Dashboard
                                <i class="far fa-list-alt"></i>
                            </a>
                        </li>
                        <li title="Cerrar sessión">
                            <a (click)="logOut()" class="dropdown-item btn d-flex justify-content-between align-items-center">
                                Salir
                                <i class="fas fa-sign-out-alt"></i>
                            </a>
                        </li>
                    </ul>
                </div>
            </ng-template>

I make use of data-bs-toogle=”dropdown” according to the bootstrap documentation

        </div>
    </div>
</nav>

When I create the same menu even outside the navbar after adding the @types it stops working, I tried to make use of other tips like the ones in this example which includes: Install @popperjs/core, Import Bootstrap as bundle

But these, in addition to not solving my problem, cause the dropdown to stop working in everything else

How to filter an array of objects by elements from another array

I have an array of objects containing information about cocktails such as ingredients, which I have fetched and sorted from an API.
This has been obtained by inputting an array of ingredients and receiving all possible cocktails containing said ingredients from the API.
I am trying to filter through this list and return the cocktails which have ingredients only found on the initial ingredient array. I want to know what drinks I can make from my ingredients and filter out the ones I cant. Below is a screenshot of my array containing the cocktail objects.

Array of objects containing drink information

I have tried to turn the objects into an array and filter them to show only the ingredients to make handling the data easier, and then tried to filter the data against my ingredients array.. but i’ve had no luck! I’ve looked at other questions but I can’t seem to translate them to this problem.

//Map array list, convert each drink object into key:value array of arrays
        const ingList = fullList.map(drink => {
            const ingArray = Object.entries(drink)
//Filter out so we only have drink id and ingredients
            const ingFilter = ingArray.filter(x => x[0].includes('strIngredient') && x[1] !== null || x[0].includes('idDrink')) 
            return ingFilter
        })
        console.log(ingList)
 let result = []
        ingList.map(x => {
            let res = x.filter(item => ingredients.includes(item[1]))
            result.push(res)
        })   
        console.log(result)

Filtered list

Full code below:

const ingredients = ['Vodka', 'Rum', 'Coca-cola', 'Orange Juice']

function getCombinations(valuesArray) {

    let combi = [];
    let temp = [];
    let slent = Math.pow(2, valuesArray.length);

    for (let i = 0; i < slent; i++)
    {
        temp = [];
        for (let j = 0; j < valuesArray.length; j++)
        {
            if ((i & Math.pow(2, j)))
            {
                temp.push(valuesArray[j]);
            }
        }
        if (temp.length > 0)
        {
            combi.push(temp);
        }
    }

    combi.sort((a, b) => a.length - b.length);
    // console.log(combi.join("n"));
    // console.log(combi.filter(x => x.length > 1))
    combi = combi.filter(x => x.length > 1)
// Fetch data with combinations array    
    let drinkList = []
    const fetchAll = async (combi) => {
        for (let i = 0; i < combi.length; i++) {
            let possible = await axios.get(`https://www.thecocktaildb.com/api/json/v2/9973533/filter.php?i=${combi[i].join(',')}`)
            let data = possible.data.drinks
            // console.log(possible.data.drinks)
            typeof(data) !== 'string' && drinkList.push(data)
        }
       // console.log(drinkList)
        //flatten array of arrays into one.
        const concatList = drinkList.flat(1)
        //console.log(concatList)
        let fullList = []
        //lookup each drink into new array with full details
        for (let i = 0; i < concatList.length; i++) {
            let res = await axios.get(`https://www.thecocktaildb.com/api/json/v2/9973533/lookup.php?i=${concatList[i].idDrink}`)
            let data = res.data.drinks
            fullList.push(data)
        }
        //Flatten array of arrays into single array
        fullList = fullList.flat(1)
        console.log(fullList)

        //Map array list, convert each drink object into key:value array of arrays
        const ingList = fullList.map(drink => {
            const ingArray = Object.entries(drink)
        //Filter out so we only have drink id and ingredients
            const ingFilter = ingArray.filter(x => x[0].includes('strIngredient') && x[1] !== null || x[0].includes('idDrink')) 
            return ingFilter
        })
        console.log(ingList)
        
        let result = []
        ingList.map(x => {
            let res = x.filter(item => ingredients.includes(item[1]))
            result.push(res)
        })   
        console.log(result)   
            // var arr1 = [1,2,3,4],
            // arr2 = [2,4],
            // res = arr1.filter(item => !arr2.includes(item));
            // console.log(res);
    }
    fetchAll(combi)
}
getCombinations(ingredients);

remove line items by property, not values, in an object

I have an object like this:

var obj = [
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 },
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 },
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 }
]

I want obj to now represent this:

var obj = [
 {
        item1: 'test',
    item2: 'something',
 },
 {
        item1: 'test',
    item2: 'something',
 },
 {
        item1: 'test',
    item2: 'something',
 }
]

I found a lot of answers about object manipulation and using keys etc

JavaScript: filter() for Objects

How to filter an object of objects efficiently?

How to filter an object with its values in ES6

The problem with these answers is

  1. its a specific object format, and they don’t cover how to do multiple objects

  2. It removes objects completely, not value and keys/line items

The closest I have it is this:

var obj = [
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 },
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 },
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 }
]

var newObj = [];

obj.forEach(function(el){
    newObj.push(el.item1);
  newObj.push(el.item2);
})

console.log(newObj)

Obviously this isn’t quite it because I need to push the full object not just the key values.

I’m trying something like this How to filter an object with its values in ES6 but this answer won’t work because it’s doing by value and not by key(?)

var obj = [
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 },
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 },
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 }
]

var acceptedProps = ['item1', 'item2'];

var newObj = Object.keys(obj).reduce(function(r, e) {
  if (acceptedProps.includes(obj[e])) r[e] = obj[e]
  return r;
}, {})

console.log(newObj)

It’s just giving me an empty array. I tried flipping some stuff around as well

var obj = [
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 },
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 },
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 }
]

var acceptedProps = ['item1', 'item2'];

var newObj = Object.keys(obj).reduce(function(r, e) {
  if (acceptedProps.includes(obj[r])) r[e] = obj[r]
  return r;
}, {})

console.log(newObj)

idk what r and e means in this function?

How do you filter objects by property and not value, for an array of multiple objects?

EDIT – okay I just found this answer:

Remove array element based on object property

var obj = [
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 },
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 },
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 }
]

var newObj = obj.filter(function( obj ) {
    return obj.field !== 'item3';
});

console.log(newObj)

So now…I have to somehow change it to a lop(?) and update each object without the line item…

var obj = [
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 },
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 },
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 }
]

var obj = [
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 },
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 },
 {
        item1: 'test',
    item2: 'something',
    item3: 'REMOVE THIS',
    item4: 'REMOVE THIS',
    item5: 'REMOVE THIS',
 }
]

var newObj = obj.forEach(function(el) {
  el.filter(function( el ) {
    return el.field !== 'item3';
  });
})

console.log(newObj)

but I get:

el.filter is not a function …

How do I do this? what am I doing wrong?

Role add discord.js

require('discord-inline-reply');
const { MessageEmbed } = require("discord.js");
const { ownerID } = require("../../owner.json")
const db = require('quick.db')
module.exports = {
  config: {
      name: "roleadd",
          description: "Add a role to a member",
              usage: "m/roleadd <member mention/id> <role mention/role id>",
                  aliases: ['role add', 'radd', 'role']
                    },
                      run: async (client, message, args) => {

    let rMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
    if(!rMember) return message.channel.send("Please provide a user to add a role too.")
    let role = message.guild.roles.cache.find(r => r.name == args[1]) || message.guild.roles.cache.find(r => r.id == args[1]) || message.mentions.roles.first()
    if(!role) return message.channel.send("Please provide a role to add to said user.") 


    if(rMember.roles.cache.has(role.id)) {
      return message.channel.send(`${rMember.displayName}, already has the role!`)
    } else {
      await rMember.roles.add(role.id).catch(e => console.log(e.message))
      message.channel.send(`${rMember.displayName} has been added to **${role.name}**`)
    }
  },
  };

The bot just gives role even if the user has a role lower than the user. I want to add a role position checking. Can anybody help?