JavaScript – Algorithm To Filter Data On Click

On the frontend the user will click on multiple options and all that will be stored in an array as objects as shown in dataToFilter variable below. Then when user clicks on search button, the array will be sent to the backend and the api route will run the algorithm filtering the data based on the items in the array and return the filtered data to the user. My question – how can I run a filter loop on the data matching the items in the array to search for? One way I can think of is checking the length of the array and setting the number of && accordingly within the filter loop but I dont think that would be the appropriate way to go about it. Thank you for reading this post.

***Dummy Data To Search From***
let data = [
{"name":"Testing", "age":32,"score": 95, "gender":"male"},
{"name":"Testing", "age":22,"score": 85, "gender":"female"},
{"name":"Testing", "age":32,"score": 85, "gender":"male"},
{"name":"Testing", "age":52,"score": 95, "gender":"female"},
]
***Filter Data***
let dataToFilter = [{"age":32},{"score": 95}]
let filteredData = []

filteredData = data.filter((item)=>{
   return item.age === 32 && item.score === 95
)

Node.JS main loop will not return

I am trying to setup a template site using Node.JS. I am new to using Node.JS and am trying to open up an HTML file and a CSS file before continuing towards the rest of the code. However, even upon reaching reponse.end(), the loop continues to run, and in fact goes for a second time, but does not make it to the end again. I threw in some console.log()s in order to demonstrate this. I will throw both my JS code and mode console output down below. I do not know how to fix this, and any help would be appreciated. Thank you all very much!

const server = require('http').createServer()
const markdown = require( "markdown" ).markdown

const fs = require('fs')

server.on('request', (request, response) => {
    response.setHeader('Content-Type', 'text/html')
    var page = fs.readFileSync("html/tb.html", 'utf8')
    console.log("reading html...")
    page+= "<style>"+fs.readFileSync("css/style.css", 'utf8')+"</style>"
    console.log("reading css...")
    const lang = Intl.DateTimeFormat().resolvedOptions().locale
  
    if (request.url === '/') {
        response.end()
    }
    else if (request.url === '/coucou') {
        page+=markdown.toHTML('#Hello world!')
        response.end(page)
        console.log("end")
    }
})

server.listen(4000)

I am sorry for my lack of NodeJS experience, but I could not seem to find an answer to this question anywhere else. Here is my console output when loading ‘coucou’:

reading html...
reading css...
end
reading html...
reading css...

And here it is on the homepage

reading html...
reading css...
reading html...
reading css...

It does not continue after the second round, but the browser never receives an end signal, and therefore continues to load indefinitely. How do I get it to actually process the end of the response and to tell my browser to stop loading?

Again, thank you all very much!!!

Popup modal with JS and PHP query

I’ve got a gallery where I have some buttons to filter the images by category. When you click an image it pops up a modal and shows the picture. It works when I open it up (at first it shows all the images) and when I choose a option 2021, but with other options it does not work. The strange thing is that when I click an image from (for example) option 2020, the modal does not show up, but when I click option 2021 the modal with the right picture shows up.
The buttons look like this:

<button data-filter=".2020">2020</button>
<button data-filter=".2021">2021</button>

I read the picture’s names from mysql database and shows it with a while loop with php.

query starts
echo '<div class="col-lg-3 col-md-6 special-grid '; echo $row["category"];  echo '">
...
<img id="myImg'; echo $db; $db++; echo'" src="gallery/'; echo $row["picturename"]; 
echo'" class="img-fluid" alt="Image" width="480" height="380">
query ends

Modal:

<div id="myModal" class="modal">
<span class="close">&times;</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>

Javascript:

<script>
var modal = document.getElementById("myModal");
var modalImg = document.getElementById("img01");
for (let i = 0; i < <?php echo $sizeofgallery ?>; i++) {
// Get the image and insert it inside the modal
   var img = document.getElementById("myImg" + i);
   img.onclick = function () {
       modal.style.display = "block";
       modalImg.src = this.src;
   }
}
var span = document.getElementsByClassName("close")[0];
span.onclick = function () {
   modal.style.display = "none";
}

</script>

Open daterangeicker inside a side menu

I would like to open a daterangepicker inside a side menu. But the darerangepicker does not stay inside the side menu. In the picture you can see that overflow-y is on the main window instead of the side meny that I want. And the layout of the daterangepicker is depenedent of the main window width and not the side menu width. What do I need to add?

<div class="mainBody">
  <div class="sidebarWrap sidebarWrapLeft">
    <div class="sidebar">  
       <input type="text" name="daterange" value="01/01/2018 - 01/15/2018" />
    </div>
  </div>
  
  
  <div class="main-page-container">
    <nav class="navbar navbar-default navbar-static-top">
      <a href="#" class="menuToggleBtn"><i class="fa fa-bars"></i></a>
    </nav>
  </div>
</div> 

overflow picure

calling new Date variable in formatWithOptions results in RangeError: Invalid time value [duplicate]

I want to display the date for each entry (date, text, question, answer) in a json database within a lit element in a js module.

Relevant code:

import { formatWithOptions } from "date-fns/fp";
import compose from "crocks/helpers/compose";

...

const newDate = (x) => new Date(x);


const formatDateWithOptions = formatWithOptions(
  {
    awareOfUnicodeTokens: true,
  },
  "d MMMM, yyyy, h:mm a"
);

const prettyDate = compose(formatDateWithOptions, newDate); // this is registering as an invalid date

When ${prettyDate(date)} is called inside a lit element, it throws

RangeError: Invalid time value.

According to the date-fns docs, formatWithOptions() should be fine to call with "d MMMM, yyyy, h:mm a". This post deals with the same error, but is using a different function (formatDistanceToNow). Where am I going wrong with my variables?

Get text with javascript textContent

I try to get text from a site, using javascript and textContent

i use this code

var markets=document.getElementsByClassName('sip-MarketGroup ')
for (var i=0;i<markets.length;i++){
    try {
       console.log(markets[i].textContent);
    } catch (error) {
       console.error(error);
    }
}

           

a part of html into the site is this below

<div class="sip-MarketGroupButton sip-MarketGroup_Open ">
    <div class="sip-MarketGroupButton_Text " style="">Fulltime Result</div>
    <div class="sip-MarketGroupButton_FavouriteButton sip-FavouriteButton ">
        <div class="sip-FavouriteButton_SVG "> </div>
    </div>
</div>
<div class="gl-MarketGroup_Wrapper ">
    <div class="gl-MarketGroupContainer ">
        <div class="gl-Market gl-Market_General gl-Market_General-topborder gl-Market_General-pwidth100 ">
            <div class="gl-Participant gl-Participant_General gl-Market_General-cn3 ">
                <span class="gl-Participant_Name">QPR</span>
                <span class="gl-Participant_Odds">12.00</span>
            </div>
            <div class="gl-Participant gl-Participant_General gl-Market_General-cn3 ">
                <span class="gl-Participant_Name">Draw</span>
                <span class="gl-Participant_Odds">4.00</span>
            </div>
            <div class="gl-Participant gl-Participant_General gl-Market_General-cn3 ">
                <span class="gl-Participant_Name">Bournemouth</span>
                <span class="gl-Participant_Odds">1.36</span>
            </div>
        </div>
    </div>
</div>

and i get

Fulltime ResultQPR12.00Draw4.00Bournemouth1.36

without spaces, how can i get this text but seperated with “;”

How NFT transaction is working on solana and how to get the price of a NFT?

Short: how can I get the certain value of an NFT on solana blockchain using web3.js?

I understand that NFT’s on solana is just a token with 1 total supply, 0 decimals, with minting disable.

I understand also, that to add metadata to solana’s NFT you need to use metaplex to create your collection and prepare the mint for candy machine.

With all of those notions I can create NFT collection on devnet (for example), minting them with my wallet or any solana’s wallet.

Now come’s the tricky part. Since you are the only one on this particular token addresss to have a token, you are the owner of this NFT. So if you want to give your NFT to someone you are just basically, giving 1 token of this NFT token address to someone else right ?

The other way to give (sell) your NFT is using auction mechanism, basically a smart contract, right?

So how do you manage to keep track of the price of a certain NFT? Like the platform you bought it can keep track of the price in their database. But there is no such record in a block of the value (in SOL or any other SPL-TOKEN) of a particular NFT.

I’ll give you an example. I am trying to display all my NFT from my PhantomWallet, and display the associated price (I am currently struggling to get the minted price)! But how can I get the certain value of an NFT on solana blockchain using web3.js or any solana compatible library.

How can I create a function which treats a passed parameter as a literal?

I am sure that this has been asked and answered before, but I can’t seem to find the right terminology to find an answer. I need to dynamically create a series of functions for later use which use certain values defined by parameters upon creation. For example:

var i = "bar";

var addBar = function(x) {
    // needs to always return x + " " + "bar"
  return x + " " + i;
}

i = "baz";

var addBaz = function(x) {
    // needs to always return x + " " + "baz"
  return x + " " + i;
}

alert(addBar("foo")); // returns "foo baz" because i = "baz"

Is there a way I can pass i to these functions so that the original value is used, and not the reference to the variable? Thank you!

How to check if a field is filled [duplicate]

I need to check if the fields and radio buttons are filled using

parentNode, childNodes, firstChild, lastChild, previousSibling, nextSibling.
 parentElement, children, firstElementChild, lastElementChild, previousElementSibling, nextElementSibling.

After checking the completeness of the fields, send a signal to second section.

I am trying but cannot get to getting the values.

  <div id="firstsection" class="Section">
        <label for="age"
          >Возраст пациента<input
            type="number"
            class="stepTwo-profile-item-textAge"
            name="age"
            min="0"
            max="80"
            maxlength="2"
            id="age"
        /></label>
        <p class="stepTwo-profile-item-smTitle">Пол</p>
        <label for="male">
          <input type="radio" name="gender" id="male" value="male" />Мужской
          <span class="stepTwo-profile-item-radionbtn"></span
        ></label>

        <label for="female">
          <input type="radio" name="gender" id="female" value="female" />Женский
          <span class="stepTwo-profile-item-radionbtn"></span>
        </label>
      </div>
    </div>
 
      

enter image description here

How to increase size of play button in audio player?

I’m working on a webpage that has audio that will be played on click. For the audio player, I just wanted there to be a play button so I removed all the elements using the display: none; feature. I’m happy with the overall look and the audio plays when clicked but I have a few problems. I want to increase the size of the play button but I’m not sure how to do it. I’ve tried playing around with the width and height of multiple elements but that hasn’t worked. There’s also a white semi-circle near the play button which I cannot get rid of. Here’s what it looks like so far Image

As you can see there are white semi-circles on the left and right side and the play button is quite small. I’d like to know how to get rid of the circles and increase the size of the button. Here’s my code:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./styles.css">
    <script src="https://kit.fontawesome.com/8711e0b6fa.js" crossorigin="anonymous"></script>

</head>
<body>
 <div class="content-wrapper">  
    <header>
        <a href="#" class="logo">[My Coily Story]</a>
        <ul>
            <li><a href="#" class="active">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </header>
</div>

<div class="collage"></div>

<div class="audio">
  <audio id="player" controls autoplay>
    <source src="1.mp3">
</div>

    
</body>
<script type="text/javascript" src="./main.js"></script>
</html>

CSS

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
   background-color: black;
   padding: 0;
   margin: 0;
   height: 100vh;
   width: 100vh;
}
header {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    padding: 1.875rem 6.25rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-family: Poppins, sans-serif;
    z-index: 10000;
}

header .logo {
    color: #fff;
    font-weight: 700;
    text-decoration: none;
    font-size: 1.563rem;
    text-transform: uppercase;
    letter-spacing: 0.313rem;

}

header ul{
    display: flex;
    justify-content: center;
    align-items: center;

}

header ul li {
    list-style: none;
    margin-left: 1.25rem;
}

header ul li a {
     text-decoration: none;
     padding: 0.375rem 0.938rem;
     color: #fff;
     border-radius: 1.25rem;

}

header ul li a:hover,
header ul li a.active {
    background: #fff;
    color: #2b1055;
}

.collage {
    background: url(./Images/1.gif);
    position: absolute;
    background-size: 100%;
    background-repeat: no-repeat;
    height: 501.5px;
    width: 755px;
    left: 350px;
    top: 150px;
    border: solid 8px;
    border-color: white;
}

.audio {
  
    position: absolute;
    top: 140px;
    left: 20px;
    background-color: black;
    height: 50px;

}

audio::-webkit-media-controls-panel {
  background-color: black;
  width: 200%;
  left: 20px;
}

audio::-webkit-media-controls-play-button{
background-color: white;
filter: invert(100%);
left: 260px;
top: 10px;
font-size: 20px;


}

audio::-webkit-media-controls-mute-button{
    display: none;
    
}

audio::-webkit-media-controls-timeline-container{
    display: none;
  
}
audio::-webkit-media-controls-current-time-display{
    display: none;
    
}
audio::-webkit-media-controls-time-remaining-display{
    display: none;
     
}
audio::-webkit-media-controls-timeline{
    display: none;
     
}
audio::-webkit-media-controls-volume-slider-container{
    display: none;
  
}
audio::-webkit-media-controls-volume-slider{
    display: none;
  
}
audio::-webkit-media-controls-seek-back-button{
    display: none;
     
}
audio::-webkit-media-controls-seek-forward-button{
    display: none;
   
}
audio::-webkit-media-controls-fullscreen-button{
    display: none;
    
}
audio::-webkit-media-controls-rewind-button{
    display: none;
     
}
audio::-webkit-media-controls-return-to-realtime-button{
    display: none;
 
}
audio::-webkit-media-controls-toggle-closed-captions-button {
    display: none;
    
}

Any help is greatly appreciated.

Run a script when API endpoint is hit, and check if that script is running when hit again – Node.js

I’m working on a node.js API that needs to start/run a time-intensive javaScript file when a certain endpoint is hit. I’ve got this working, but what I’m now looking for is a way to stop the script from running again if it’s already running and the endpoint gets hit again.

I tried to use the child_process library, hoping that if the script is being executed as a separate process from the main node.js app, it would be easier to check if the script is already running. I thought of using the process exit event for the child process that I created, but this proved to be unhelpful because it would only run once the process was done, but didn’t help in checking if it was currently running.

I also had considered cron jobs, but there doesn’t seem to be a good way to just start a cron job on command without making a time-based schedule.

In another project, I used a database and simply created a new row in a table to indicate whether the script was available to run, currently running, or finished. I could definitely do it this way again, but I’m trying to keep this project as light as possible.

Lastly, I did consider just adding some global state variable that would indicate if the process is running or not, but wasn’t sure if that was the best method.

So, if anyone either knows a way to check if a child process script is currently running or has a better way of achieving what I’m trying to achieve here, any direction would be helpful.

Filter json based on key and match it against one of the values from array

I have json file: products.json:

[
{
"id": "1",
"category": "Fruit from USA",
"name": "Banana",
},
{
"id": "2",
"category": "Fruit from Brazil",
"name": "Long Banana",
},
{
"id": "3",
"category": "Vegetable",
"name": "Carrot",
},
{
"id": "4",
"category": "Car from USA",
"name": "Ford",
},
{
"id": "5",
"category": "Car from Germany",
"name": "Audi",
},
{
"id": "6",
"category": "Train from Italy",
"name": "Pendolino",
},
]

Then I have an array

testMatch.match: ['Car', 'Fruit'].

I want to filter out products.json to return only objects that have category starts with any of elements of matchCategory in ES6

What i have so far is:

const productList = products.filter(filteredCategory => filteredCategory.category.startsWith(testMatch.match));

But it does not work if there is more than 1 element in testMatch.match and if there is none – it returns all products and not none.

cast numbers to strings in a nested object (nodejs)

assuming a complex nested object such as:

{ a: [{b: 12}, {c: {r: [1, 2, {g: 55} ] } }, 5], f: {h: 76}}

I’d like to cast all numbers to strings in nodejs. external libraries (e.g. lodash) are encouraged.

{ a: [{b: '12'}, {c: {r: ['1', '2', {g: '55'} ] } }, '5'], f: {h: '76'}}

Thank you!

Why does only the first CSS class of my project working and not the rest

I am using React with CSS and for some reason, my CSS doesn’t show up. Let me demonstrate.

I have my “App.js” with this code:

import './App.css';

function App() {
return(
    <div>
      <p className="wow">hhh</p>
      <p className="pow">hhh</p>
    </div>
  );
}
export default App;

And I have my App.css with this code:

.wow {
  color: blue;
};

.pow {
  color: red;
};

When I look in my browser only the first class is working and the letters are blue but not the second one or any other after. If I create a new component and import a CSS document to it as I did in the previous one the same thing will happen, the first CSS class will work and that’s all after that non of the classes work.