Filter Array of objects with nested array

so I am trying to set up a nested filter on an array of objects.
The thing is that the filter is applied inside the object on a key that is another array of objects.

here is the code:

const items = [
  { name: "123", id: 1, value:  true, arr: [{ id: 1 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 2 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 3 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 4 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 5 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 6 }] },
];

const newArray = items.filter((objects) => {
  objects.arr.filter((item) => {
    if (item.id === 2) {
      return objects;
    }
     
  });
});
console.log(newArray);

I ‘m not sure where to put the return because in this situation i just get an empty array.

Multiply javascript generated number by another number

How can i get the current number in a span and multiply it by 0.95? The number in the span is gotten from a range slider that starts from 0.003 to 0.075 below is the code i have

const uaaz = +document.querySelector("#maaz").textContent
const result = document.querySelector(".result")

function ug(ue) {
  up = ue * 0.95
  result.textContent = up
}
ug(uaaz)
<span id="maaz" class="aaz">number generated from range slider shows here</span>
<span class="result"></span>

The problem i have is that 0.003 is always the number being multiplied by 0.95 even if the number from the slider is higher. How can i make sure the current value in the span is used?

i want two make compare in foreach loop to compare if value of branch from jquery equal to value from foreach then selected it

I have a select and get value from jquery and want to compare it with value in foreach if two value id is similar then active the selected value how can i do this this is the foreach in blade:

i want two make compare in foreach loop to compare if value of branch from jquery equal to value from foreach then selected it

<select name="branch">
@foreach($branchs as $branch)
    <option value="{{$branch->id}}">{{$branch->title}} 
    </option>                                              
@endforeach
</select>

$.ajax({
url:getHref,
data:{id:id},
}).done(function(data) {
$.each(data, function(index,employee){
$( “input[name*=’name’]” ).val(employee.name );
$( “select[name=’branch’]”).val(employee.branch_id);
$( “select[name=’role_id’]” ).val(employee.role_id);
});
});
});

React: How do I prevent the usage of useRef and useState to keep track of a same value in order to prevent useEffect from triggering?

currently I am making a navbar that only shows when you scroll up, to prevent useEffect to run everytime when the visible state get changed, I had to use both a ref and a state that is synced together to do comparison in the useEffect, using ref and a state to keep track of a same value seems extremely fishy, is there another way of doing this? one that does not involve triggering useEffect from creating the event handlers everytime the state changes?

import React, { useState, useRef, useEffect } from 'react';
import Link from 'next/link';

const NavbarLink = ({ name, href }: { name: string, href: string }) => {
  return (
    <Link href={href}>
      <a>{ name }</a>
    </Link>
  );
}

const Navbar = () => {
  const scrollYRef = useRef(0);
  const visibleRef = useRef(true);
  const [visible, setVisible] = useState(true);

  useEffect(() => {
    const onScroll = (event: Event) => {
      event.preventDefault();
      if ((window.scrollY < scrollYRef.current) != visibleRef.current) {
        visibleRef.current = !visibleRef.current;
        setVisible(x => !x);
      }
      scrollYRef.current = window.scrollY;
    }

    window.addEventListener('scroll', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
    }
  }, []);

  return (
    <div className={`${!visible && '-translate-y-full'} fixed flex w-full h-32 font-bold text-white transition-all`}>
      <NavbarLink name="home" href='/'/>
    </div>
  );
}

javascript nested object and arrays adding new element problem

here is my code piece

const date = new Date()
let exactTime = date.toLocaleString('en-KL', { hour: 'numeric', minute: 'numeric', hour12: true })

const signUp = (username,email,password,isLoggedIn) => {
    let obj = {
        _id: 'ddfcd',
        username: username,
        email: email,
        password: password,
        createdAt:`${date.getDate()}/${date.getMonth()}/${date.getFullYear()} ${exactTime}`,
        isLoggedIn: isLoggedIn
    }
    let arr = [`${users2.length}`, obj]
    let collection = Object.entries(users2)
    collection.push(arr)
    users2 = collection
}

signUp('ali','[email protected]','123',false)
signUp('kerem','[email protected]','456',false)
signUp('johndoe','[email protected]','789',true)

when i get new user data at first the new one is exacrly similar with the rest however when add second one (or more) it misses an array it just turns array into object

here is the example what i mean when i add one more user then the previous one gets normal

what’s the problem here

Unable to get graphql response from server that’s running on local

I have a mongodb server setup which on running the below command starts on port 3000

npm run start 

I also a graphql server which on running the below command starts at port 4000

npm run start-graphql

the scripts of my package.json is as below

"scripts": {
    "start": "nodemon server.js",
    "start-graphql": "nodemon graphqlserver.js",
    "test": "echo "Error: no test specified" && exit 1"
  },

server.js

require('dotenv').config();
const express = require('express');
const app = express();
const mongoose = require('mongoose');
mongoose.connect(process.env.DATABASE_URL);
const db = mongoose.connection;


db.on('error', (err) => console.log(err));
db.once('open', () => {
    console.log("Backend Database connected");
});


app.use(express.json({ limit: '2mb'}));

const photosRouter = require('./routes/photos');
app.use('/images', photosRouter)


app.listen(3000, () => {
    console.log('Server started at port 3000');
})

graphqlserver.js

const express = require('express');
const path = require('path');
const express_graphql = require('express-graphql').graphqlHTTP;
const { loadSchemaSync } =  require('@graphql-tools/load');
const { GraphQLFileLoader } = require('@graphql-tools/graphql-file-loader');
const { addResolversToSchema } = require('@graphql-tools/schema');

const getResolvers = require('./graphql/resolvers');

// GraphQL schema
const combinedSchema = loadSchemaSync(
    path.join(__dirname, './graphql/schemas/*.graphql'),
    {
      loaders: [new GraphQLFileLoader()],
    }
  );
const schema = addResolversToSchema({
    schema: combinedSchema,
    resolvers: Object.assign({}, getResolvers())
  });

// Create an express server and a GraphQL endpoint
const app = express();

app.use('/graphql', express_graphql({
    schema: schema,
    graphiql: true
}));
app.listen(4000, () => console.log('Express GraphQL Server Now Running On localhost:4000/graphql'));

when I call the rest api’s normally either through postman or curl it returns the response as expected.

For eg: http://localhost:3000/images returns me an array of objects

But When I want to call (using axios) the same via the graphql server (which is running on port 4000 ),
I get response as null.
I have no clue why this is happening.
Please check the below screenshot for your reference
enter image description here

Note: For better clarity please check the codebase link
https://github.com/yaswankar/G-photos-backend

Any help would be appreciated.

Thanks in advance

VueJS Style Guide – Coding Standard

I’m coming from PHP and Laravel and I know there is coding standard for different frameworks like PSR. However, when I searched the internet I can not find proper way to stylize my code or any standard. I know there is some style guides like Airbnb style guide but it is just a guide. I like to see how to chain, where to split the code, when it exceeds 120 chars or 80 chars, things like that.

I like to my code persistent and properly formatted. Do you have any recommendation about it?

How to print “-1” if sudoku has no solution?

I have solved the sudoku using JavaScript but I want to print -1 if the given sudoku has no solution. I have done it using recursion and have exhausted all the ways that I could think of. Please help me solve this question for unsolvable sudoko’s.

let row = 0;
let col = 0;
let matrix = [
    [0, 4, 0, 0, 0, 0, 1, 7, 9],
    [0, 0, 2, 0, 0, 8, 0, 5, 4],
    [0, 0, 6, 0, 0, 5, 0, 0, 8],
    [0, 8, 0, 0, 7, 0, 9, 1, 0],
    [0, 5, 0, 0, 9, 0, 0, 3, 0],
    [0, 1, 9, 0, 6, 0, 0, 4, 0],
    [3, 0, 0, 4, 0, 0, 7, 0, 0],
    [5, 7, 0, 1, 0, 0, 2, 0, 0],
    [9, 2, 8, 0, 0, 0, 0, 6, 0]
];

function sudoku(matrix, row, col) {
    if (row == 9) {
        console.log(matrix);
        return;
    }

    let next_row = 0;
    let next_col = 0;
    if (col == 8) {
        next_col = 0;
        next_row = row + 1;
    }
    else {
        next_col = col + 1;
        next_row = row;
    }
    if (matrix[row][col] != 0) {
        sudoku(matrix, next_row, next_col);
    }
    else {
        for (let i = 0; i <= 9; i++) {
            if (isSafe(matrix, row, col, i) == true) {
                matrix[row][col] = i;

                sudoku(matrix, next_row, next_col);
                matrix[row][col] = 0;
            }
        }
    }
}

function isSafe(matrix, row, col, value) {

    for (let i = 0; i < matrix.length; i++) {
        if (matrix[i][col] == value) {
            return false;
        }
    }

    for (let i = 0; i < matrix.length; i++) {
        if (matrix[row][i] == value) {
            return false;
        }
    }

    let x = Math.floor(row / 3) * 3;
    let y = Math.floor(col / 3) * 3;

    for (let i = 0; i < 3; i++) {
        for (let j = 0; j < 3; j++) {
            if (matrix[x + i][y + j] == value) {
                return false;
            }
        }
    }
    return true;
}

sudoku(matrix, row, col);

Example of sudoku with no solution:

let matrix = [
    [0, 0, 0, 0, 5, 4, 3, 0, 6],
    [0, 0, 0, 0, 0, 3, 2, 7, 0],
    [0, 0, 0, 7, 2, 0, 0, 0, 1],
    [9, 0, 0, 0, 7, 0, 0, 5, 3],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [8, 2, 0, 0, 1, 0, 0, 0, 9],
    [3, 0, 0, 0, 6, 1, 0, 0, 0],
    [0, 4, 6, 9, 0, 0, 0, 0, 0],
    [7, 0, 1, 5, 4, 0, 0, 0, 6]
];

How to use file option for each elements of list, and pass its value into controllers using jQuery

I am at beginner level for using Jquery.

Problem : so the problem is that, I have to add “choose file” for each of the element’s inside a tag. And display the image after selecting it inside the tag. But Has this is this list of elements using for each loop, it cannot different between the id property.
please see the images and code for reference and help me out,
Thank You !!!

[.cshtml]
@if (Model.DailyMenuProducts != null && Model.DailyMenuProducts.Count > 0)
{
@for (int i = 0; i < Model.DailyMenuProducts.Count; i++)
{
 <li class="list-group-item">
    <input asp-for="@Model.DailyMenuProducts[i].IsChecked" type="checkbox" />
    <label asp-for="@Model.DailyMenuProducts[i].ProductId">  @Model.DailyMenuProducts[i].ProductName</label>
    <input type="hidden" asp-for="@Model.DailyMenuProducts[i].ProductId"/>
    <input type="hidden" asp-for="@Model.DailyMenuProducts[i].ProductName" asp-route-productId/>
        <div  class="uploadFile float-end">
            <label for="productImage">
                <img id="imageViewer" width="50" height="50" style="border: 1px solid #000000; cursor:pointer;" />
            </label>
            <input asp-for="@Model.DailyMenuProducts[i].ProductImage" asp-for-ProductId="@Model.DailyMenuProducts[i].ProductId" type="file" id="productImage" style="display:none; visibility:none" onchange="getImage(this.value);"/>
         </div>
</li>
}

[.js]

$(".uploadFile").on('change', function () {
        console.log('new file uploaded')
        //var array = $("#productImage").getIdArray();
        var file_data = $("#productImage").prop("files")[0];
        var files = event.target.files
        $("#imageViewer").attr("src", window.URL.createObjectURL(files[0]));
        var form_data = new FormData();
        var product_Id = (this.ProductId) ;
        var viewModel = { ProductId: product_Id, ProductImage: file_data};
        form_data.append("file", file_data);
        $.ajax({
            url: "/DailyMenuPlanner/AddPhoto",
            cache: false,
            contentType: false,
            processData: false,
            data: viewModel,
            type: 'post',
            success: function (result) {
                if (result.success == true) { alert("success!"); }
                else { alert("fail!"); }
            }
        });
        
    });

In this image you can see that each elements have choose file option, and i have selected image for the first one and so the image is reflecting there! but if i select image for 2nd element then it effect only for 1st element and image of 1st element will change not for the 2nd element

Possible async problem with firebase get request

I have a function useVenue that returns venue data from a call to firebase:

import { useState,useEffect } from 'react'
import { firebase } from './firebaseConfig'

export  function useVenues (){
  const [venues, setVenues] = useState([]);
  useEffect(() => {
    const venueArray = [];
    const getAllVenues = async () => {
      await firebase
        .firestore()
        .collection("venues")
        .get()
        .then((snapshot) => {
          snapshot.forEach((venue) => {
            venueArray.push(venue);
          });
          setVenues(venueArray);
        });
    };
    getAllVenues();
  }, []);

  const [...venueData] = venues.map((venue) => {
    
    const { 
      name, 
      photoUrl, 
      averageRating, 
      numRatings, 
      type,
      address,
      phone,
      website,
      reviews } = venue.data();

    return ({
      name: name,
      photoUrl: photoUrl,
      averageRating: averageRating,
      numRatings: numRatings,
      type: type,
      id: venue.id,
      reviews:reviews,
      address:address,
      phone:phone,
      website:website
    })
  });
  return {venueData}
};

This function is exported to venues.js where the venue data is destructured out and pass as props to MidSection.js:

venues.js

import { useParams } from 'react-router-dom';
import { useVenues } from '../useVenue';
import Header from '../components/Header'
import VenueDetails from '../components/venue-page/VenueDetails'
import MidSection from '../components/venue-page/MidSection';
import ReviewSection from '../components/venue-page/ReviewSection';

const Venue = () => {

    let {id} = useParams()
    const { venueData } = useVenues()

    const filteredVenue = venueData.filter(item => {
        return item.id === id
    })

    return(
        <div>
            <Header/>
            <VenueDetails filteredVenue = {filteredVenue}/>
            <MidSection filteredVenue = {filteredVenue}/>
            <ReviewSection filteredVenue = {filteredVenue} id = {id}/>
        </div>
    )
}

export default Venue

Lastly, in mid section I want to pull some information out of the venue data, passed as props as filteredvenue. I’m extracting this data with the following function:

import { useEffect,useState } from 'react'
import { convertToStars } from "../../helperFunctions";

const MidSection = ({ filteredVenue }) => {


  const extractRatings =   () => {
    const foodRatings = []
    filteredVenue[0].reviews.map((rating) => {
     foodRatings.push(rating.ratingFood)
    })
    return {foodRatings}
  }

  const {foodRatings} = extractRatings()

I logged out foodRatings and it returned the data I wanted. However when I refreshed the browser, the app crashed, giving the error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘reviews’)

I’m assuming this is some sort of asynchronous error and that the browser is rendering this component before the data has been returned. Unsure why this is happening since I’m using async/await in the initial firebase useVenues function, and the filteredVenue object is being mapped through elsewhere in this component with no problems. Suggestions?

Javascript- What is the difference between the thread pool and web API for handling asynchronous behavior?

Motive

For Javascript and node.js, I am trying to understand the difference between the thread pool and Web API.

What I Currently Understand

  • Thread pool: a multi-thread platform, where each thread executes their own operation.
  • Web API: an API built in to the browser. It is part of the event loop, along with the call stack and callback queue to enable asynchronous operations in Javascript.

What I Am Confused about

It seems like both the thread pool, and Web API, enable Javascript to handle asynchronous behavior.

When Javascript is executing code off the singly-threaded call stack, is it sent to the Web API, which uses a thread pool to create a single thread for each asynchronous operation?

If not, how does the Web API and thread pool work together to give Javascript asynchronous capabilities?

Calculate the required height for the right amount of scrolling

I’ve found this working example here: Use Vertical Scrollbar to Horizontal Scroll Content. It’s great except that I’d have to give a random height to #fakecontent. I’d like that when I scroll all the way down, I’d just arrive at the end of the horizontal slider. Not too far, not too close.

I tried to find the required ratio with no luck. with / height etc etc

How is finding the correct height of #fakecontent achievable?

$(window).on('scroll', function() {
  $("#realcontent").css("left", -$(window).scrollTop());
});
#realcontent {
  background-color: #333;
  position: fixed;
  top: 5px;
  left: 0;
  width: 2000px;
  color: #fff;
  height: 100px
}

#fakecontent {
  height: 2000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="realcontent">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ullam a est maiores fugiat nesciunt, at ad. Tempore odio velit ipsam, laborum explicabo repudiandae aliquid nostrum qui dolorem obcaecati, autem expedita!</div>
<div id="fakecontent"></div>

How to filter array to match params value with react

I wanted to create a e-commerce web application using react-bootstrap. I want the page to show different item based on category so if the URL is product/men’sclothing i want to filter my array and show only the product that have same category which is men’s clothing (my path: product/:category). I already tried to filter my array using .filter method but it didn’t work, it still show all product from various category, How can I fix it ?

Categorized product page:

const ProductList = () => {
  const { category } = useParams()
  const[productList, setProductList]= useState();

  useEffect(() =>{
    axios.get(`https://fakestoreapi.com/products`).then(res => {
        const products = res.data;
        setProductList(products);

        var filteredCategory =
         productList.filter((productList) =>productList.category === {category})
      })
  }, []);

  console.log(productList)

  return (
    <>
      <Row>
        <h1> This is {category} paged</h1>
        {productList && productList.map(product =>{
          const {id, title, price, category,description,image} = product;
          return(
          <Col lg={3} className="d-flex">
            <Card key={id} className="flex-fill productlist">
              <Card.Img variant="top" src={image} />
              <Card.Body>
                <Card.Title>{title}</Card.Title>
                <Card.Text>{category}</Card.Text>
                <Card.Text>
                  Current Price: {price}
                </Card.Text>
                <Button variant="primary">Add to cart</Button>
              </Card.Body>
            </Card>
          </Col>
          )
        })}
      </Row>
    </>
  )
}

export default ProductList