JavaScript – specific queried from two databases

I need help with a JavaScript task.
How do I get something specific queried from two databases?

Task:
View the index.js file
Implement the gradeOverview() function, which gets the variables students and
grades and creates a grade overview for each student. Thereby
each element in the students array should be projected to an object in the following format:
{ student: (students[i]), grades: [(grades[j], grades[j+k], …)] }

This is my function which accesses both databases and should retrieve and display a value from one database at a time based on the “student number”.

    function gradeOverview(students, grades) {
      const result = students.map((student) => [
        {
          student: student,
          grade: grades.reduce((grades, grade) => {
            const student number = grade.studentnumber;
            if (grades[matriculationnumber] == null) grades[matriculationnumber] = [];
            grades[matriculationnumber].push(grade);
            return grades;
          }),
        },
      ]);

  console.log(result);

  return result;

  // TODO: implement me
}

How to search for items in array properties? [duplicate]

I am trying to make a simple website(without CSS3) to search for items in an array. My way of accomplishing this goal is to search in the ‘title’ or ‘desc’ properties of an item in the array. My expected result is to get titleOfItem + ‘ fizz’ in the console if the title includes the keyword from the input. Instead, I get the following error:
console image & error
EDIT: I fixed this by adding a condition instead of a number in the for loop.

Here is my HTML5 code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>replit</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <input id="keywordText" type="text">
    <button id="submit" onclick="search()">Search</button>
    <script src="script.js"></script>
  </body>
</html>

and Here is my JS code:

const items = {
  john:{title:'john', desc:"doe", elem:document.getElementById('john')},
  jane:{title:'jane', desc:"doe", elem:document.getElementById('jane')}
}

let allItems = []
for (var key in items) {
  allItems.push(items[key])
}



function search() {
  let keyword = document.getElementById('keywordText').value;
  for (let count = 0; allItems.length; count++) {
    let titleOfItem = allItems[count].title
    if (titleOfItem.includes(keyword)) {
      console.log(titleOfItem + ' fizz')
    } else {
      console.log(titleOfItem + ' buzz')
    }
  }
}

Is there something that I am doing wrong in this code? Also, for organization purposes, is there some way to get this information straight from the first array?

Thank you for your help!

My coupon checking codewars program has an unexplained error

function checkCoupon(enteredCode, correctCode, currentDate, expirationDate) {
  const months = 'January February March April May June July August September October November December'.split(' ');
  if (enteredCode != correctCode) return false;
  
  if (Number(currentDate.split(' ')[2]) > Number(expirationDate.split(' ')[2])) return false;
  
  else if (Number(currentDate.split(' ')[2]) == Number(expirationDate.split(' ')[2])) {
    for (let x = 0; x < months.length; x++) {
      if (months[x] == currentDate.split(' ')[0]) {
        for (let y = 0; y < months.length; y++) {
          if (months[y] == expirationDate.split(' ')[0]) {
            if (x > y) return false;
            else if (x == y) {
              if (Number(currentDate.split(' ')[1].replace(',', '')) > Number(expirationDate.split(' ')[1].replace(',', ''))) return false;
              else return true;
            }
            else return true;
          }
        }
      }
    }
  }
  
  else return true;
}

I’m doing a 7 kyu codewars kata called “The coupon code” and the program I’ve made completes all of the tests except three. All 3 of them say they expected false and instead got true. I’ve tried to see the problem in my code for over 45 minutes, but haven’t made any progress because codewars doesn’t allow users to see the conditions of the tests, only the outputs. I’m aware that there is a Date object within JavaScript that I could use to remedy this problem. I intentionally opted against using this for the sake of developing problem solving skills. Does anyone have advice that could help nudge me in the right direction?

CSS transitions not visible when screen-recording using Puppeteer

I have a page where lots of large images are being resized and moved around and I am using CSS transitions for all of these actions.

When I run the page on the browser everything is working fine.

The transitions are sometimes a bit bumpy but it’s understandable given the size of the images and the large quantity so I can live with that.

However, I’m now trying to use puppeteer (headless) combined with the puppeteer-screen-recorder module and when I look at the resulting video, there are no transitions.

import puppeteer from 'puppeteer'
import { PuppeteerScreenRecorder } from 'puppeteer-screen-recorder'

const defaultViewport = {
  width: 1440,
  height: 764
}

;(() => {

  const browser = await puppeteer.launch({ defaultViewport })
  const page = await browser.newPage()
  const recorder = new PuppeteerScreenRecorder(page, {
    videoFrame: defaultViewport,
    aspectRatio: '360:191'
  })

  async function stop() {
    await recorder.stop()
    await browser.close()
    process.exit(1) 
  }

  await page.setDefaultNavigationTimeout(0)

  await page.exposeFunction('onAnimationsDone', async () => {
    stop()
  })

  await page.exposeFunction('onAnimationsStarted', () => {
    recorder.start('./client/db/test.mp4')
  })

  await page.goto('http://localhost:8000/')

})()

Is this an unavoidable limitation of using headless puppeteer or am I doing something wrong ?

Replace User Text Input In Chrome Extension

I currently have this code that will replace specific cases user input with other characters and it works in browser. However, when I try to do this in a google chrome extension, the text does not get replaced. Is there a way to make it work for chrome extensions?

$('body').on('input', 'input[name=address1]', function() {
  $(this).val($(this).val().replace('/', ' m. '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="text" name="address1" id="address1" value=""/>

React Native route.params is undefined

I’ve been trying to pass data from my home.js screen to my merchant.js screen by using navigation.navigate(‘Merchant’, store ) but when I try to actually use route.params I get undefined.

Here’s my home.js

export default function Home( { navigation }) {
...
{storeData.map(store => {
    return (
     <View>
      <TouchableOpacity>
        <Text style={styles.categoryName}
          onPress={() => {navigation.navigate('Merchant', store)}}>
         {store.name}
        </Text>
      </TouchableOpacity>

Merchant.js

function Merchant({ navigation, route }) {
    console.log(route);
...
}

Output:

{“key”: “Merchant-86K9u5ytF32VGMRcO9s2g”, “name”: “Merchant”, “params”: undefined}

Again I have no idea what is going on. I’ve tried navigation.push(), I’ve tried using navigate(‘Merchant’, {name: store.name}) but I still get undefined.

If you would like to paste more code with my stack navigation I can.

Checking for validation using a switch statement

I am trying to set up conditional rendering using in the backend for allowing a user to update their profile. My first thought was to use a switch statement since it is a case by case on what they want to update (username, location, etc.), however I cannot get the validation to work case-by-case. Is there a more efficient way of doing this without using ReactJS? Below is the code and error log. I have removed the “break” clause in order for the switch to keep going in checking for an actual value. I have also tried “.trim().length” as part of the validation but the validation error i posted keeps popping as well.

profile.js

router.post("/update/:id", (req, res) => {
  console.log("UPDATING ROUTE HIT n");

  try {
    console.log("MADE IT INSIDE THE TRY ROUTE n");
    if (req.isAuthenticated()) {
      User.findOne({ id: req.params.id }, (err, foundUser) => {
        if (foundUser) {
          console.log("FOUND USER n");
          const newUpdate = {
            username: req.body.username,
            company: req.body.company,
            location: req.body.location,
            position: req.body.position,
          };
          switch (true) {
            // THIS IS THE PROBLEM
            case newUpdate.username !== "" && newUpdate.username !== User.find({ username: { $ne: null } }):
              foundUser.username = newUpdate["username"];
            case newUpdate.company !== "" && newUpdate.company.length >= 3:
              foundUser.company = newUpdate["company"];
            case newUpdate.location !== "" && newUpdate.location.length >= 3:
              foundUser.location = newUpdate["location"];
            case newUpdate.position !== "" && newUpdate.position.length >= 3:
              foundUser.position = newUpdate["position"];
              break;
            default:
              console.log("FAILED TO ENTER ANYTHING" + err + "n");
              break;
          }
          foundUser.save((err) => {
            if (err) {
              console.log("THERE WAS AN ERROR: " + err + "n");
            } else {
              console.log("SUCCESSFULLY CHANGED POSITION");
            }
          });
          res.redirect("/profile");
        } else {
          console.log("FOUND THE ANSWER" + err + "n");
        }
      });
    }
  } catch (error) {
    console.log("THERE WAS AN ERROR(caught): " + error + "n");
  }
});

enter image description here

Javascript Class, with one parameter passed to array;

I am trying to invoke a class with the code below:

class matchDetails {
        constructor(game, kit, player){
            this.game       = game;   // This remains static;
            this.kit        = color;  // This remains static;
            this.player     = new Array(player);
        }
        addMatchDetails(){
            // return "Coventry";
        }
    }
    
    ab = new matchDetails(23, 'red', 11);

On the constructor I want this.player to be an array where I can push additional values but I cannot fathom out how to code it.

Text content overflow its element tag

Here’s the code. It’s in Angular if that has something to do with it. The actual text height is overflowing the element that contains it.

html

<p id="website-title">Poll App</p>

css

#website-title {
    text-align: center;
    // font-family: "Roboto-Mono";
    font-size: 50px;
    margin: 0;
    position: absolute;
    top: 50%;
}

result
result

I want the element to be the height of the content. Any ideas? thx.

How to get all objects and count booleans (JS)

Let it be like this for example:

let data = {
    first: {
        surname: 'Miller',
        age: 37,
        gender: male,
        stealer: true
    },
    second: {
        surname: 'Connor',
        age: 28,
        gender: male,
        stealer: true
    },
    third: {
        surname: 'Smith',
        age: 13,
        gender: female,
        stealer: false
    }
}

How can I get everything at once and count booleans of false, without the need to manually enter each one individually?

Using lookup in mongodb to write a union query

Can someone please help me to make a union query:

I have all of the jobs that were created between a time period.

[{
    _id: '61be471835364400005ee66a',
    created: '2021-12-18T20:39:52.279Z',
    company: '61be44cb8c18cd0000be2048'
  }]

I got this doing an aggregate query:

const jobs = await Job.aggregate([
    {$match: ...},
    {$project: ...},
]);

I have a collection of companies, and am trying to get the COMPANY name to be pulled over into the query, rather than having to get it client side. I have the _id already in the aggregate query result. I have been trying to do this:

 const jobs = await Job.aggregate([
    {$match: ...},
    {$project: ...},
    {$lookup: {
    from: 'Company',
    localField: 'company',
    foreignField: '_id',
    as: 'result'
    };
]);

I was thinking that this would 1) get the Company that has an _id that matches our ‘company’ object ID above and 2) save that in the result field. There is nothing there, despite the object id being a match! Could someone please help walk me through how this should work? I could do it very easily I think in SQL.

Cannot synchronize functions to parse data and then visualise it

I have written this code to parse a csv file and then use this data to render a bar chart. I have tried to account for asynchronous functions using async/await, but for some reason my code is not working. When I run it the chart loads but the bars only render when I resize the window. Please could someone point out what I am doing wrong?

function parseData (dataFile){
    var barLabels = []
    var barData = []
    d3.csv(dataFile).then(function(datapoints) {
        for (i=0; i < datapoints.length; i++){
            barLabels.push(Object.values(datapoints[i])[0]);
            barData.push(Object.values(datapoints[i])[1]);
        }        
    });
    return [barLabels, barData];
}

function makeChart(dataX, dataY, canvasID){ 
    var ctx = document.getElementById(canvasID)
    var chart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: dataX,
            datasets: [
            {
                label: "Carbon Footprint of Leading European Apparel Brands in 2019",
                data: dataY,
                              
            }]
        }, 

    });

    
}


async function renderChart(file){
    let chartData = await parseData(file);
    makeChart(chartData[0], chartData[1], 'chart')
}

renderChart('carbon-footprint-of-apparel-brands-2019.csv')

How can you the return the largest Height value out of multiple divs using jQuery or JavaScript

I am trying to return / output the largest Height value out of multiple divs within an alert using jQuery or JavaScript. I’ve tried a few examples but I think I’m going about it the wrong way. I decided to use Math.max but I think that incorrect.

My code

    $(".go-buttn").click(function(){
        var sum = 0;
        var x = document.querySelectorAll(".col-lg-6.col-md-12.col-sm-12 .block");
        var maxValueInArray = Math.max.apply(Math, x);
        alert($(maxValueInArray).height());
    });


    <button class="go-button">Click me </button>

    <div> //This first div should return the tallest value in height
        <p>
        test 
        </p>
        <p>
        test 
        </p>
        <p>
        test 
        </p>
    </div>

    <div>
        <p>
        Test  
        </p>
    </div>

    <div>
        <p>
        Test  
        </p>
    </div>

Wait for completion of callback function in HTTP request before continuing with for loop

I’m trying to run an HTTP request 3 times in node.js using the inbuilt HTTPS library, with each run having a different set of options. In order to move on to the next set of options after the completion of one execution, I”m using a for loop that increments once each run, for a total of 3 runs. However, instead of waiting for each run to finish before proceeding in the loop, it skips the first two calls completely and runs it 3 times with the third set of options. I’ve looked all over for an answer, anyone have any ideas/solutions?

    for(let i = 0; i < 3; i++) {
        option = i;
        console.log("Calling with option " + i)
        await http.request(options[i], res => {
            let resp = '';
            res.on('data', function(chunk) {
                resp += chunk;
            });
            res.on('end', async function () {
                let data = await JSON.parse(resp);
                if(option === 0) { //Bloxlink handler
                    console.log("Case 1: Bloxlink")
                    if(data.status === "error") {
                        returndata += "Bloxlink returned no users"
                    } else {
                        returndata += "nBloxlink returned user with ID " + data.primaryAccount + " and username " + await noblox.getUsernameFromId(parseInt(data.primaryAccount)) + "."
                    }
                } else if(option === 1) { //RoWifi handler
                    console.log("Case 2: RoWifi")

                    if(data.success === false) {
                        returndata += "RoWifi returned no users"
                    } else {
                        returndata += "nRoWifi returned user with ID " + data.roblox_id + " and username " + await noblox.getUsernameFromId(data.roblox_id) + "."
                    }
                } else if(option === 2) { //Eryn handler
                    console.log("Case 3: Eryn")
                    if(data.status === "error") {
                        returndata += "Eryn returned no users"
                    } else {
                        returndata += "nEryn returned user with ID " + data.robloxId + " and username " + data.robloxUsername + "."
                    }
                }
                console.log(returndata);
            });
            res.on('error', function () {
                channel.send('One or more APIs returned an error. The operation has been terminated.')
            });
        }).end();
        channel.send("Run " + i + " finished: " + returndata);
        console.log(returndata);
    }