Fill tag using text in array

I’m new to JavaScript, so I’m not sure what keywords to search to find my specific answer. Thanks in advance for your help.

I need to dynamically create li tags with a hrefs in the nav. These will scroll to 4 different sections in main.
I have created each li and a href.
I now need to get the text from each h2 to the a element in each li
I have started by creating an array from the h2 elements, but now realized that I could use the outerHTML from the previous array.
How can I get the h2 text, or access the outerHTML property from the sectionIds array?

//creates a element and assigns to  listItemHref
const listItemHref = document.createElement('a');
//assigns #nav_list or ul to variable navList
const navList = document.querySelector('#nav_list');
//creates array from id's in section elements
const sectionIds = Array.from(document.getElementsByTagName('section'));
//creates array of h2
const sectionH2 = Array.from(document.getElementsByTagName('h2'));  

for (section of sectionIds){
    //creates a <li> element for each section name
    const listItem = document.createElement('li');
    //creates an <a> element for each section name
    const listItemHref = document.createElement('a');
    //sets the "href" for each <a> element
    listItemHref.setAttribute("href", "#" + section.id);
    listItem.setAttribute("class", "line_item");
    listItem.appendChild(listItemHref);
    navList.appendChild(listItem);
}

//code to take h2 text and insert into a tag text
for (heading of sectionH2){
    // ? not sure 
}
<header class="page_header" id="home">
  <h1>Resume</h1>
    <!--each li is created using JavaScript-->
  <nav class="nav_menu">
      <ul id="nav_list">
    <li class="line_item">
      <a href="#education"></a></li>
    <li class="line_item">
      <a href="#my_projects"></a></li>
    <li class="line_item">
      <a href="#about"></a></li>
    <li class="line_item">      
      <a href="#contact"></a></li>
    </ul>
    </nav>
</header>
<main>
  <section id="education">
    <h2>My Education</h2>
  </section>
  <section id="my_projects">
    <h2>My Projects</h2>
  </section>
  <section id="about">
    <h2>About Me</h2>
  </section>
  <section id="contact">
    <h2>Contact Me</h2>
  </section>
</main>

Building a tree from a flat array

I am given an array, links:

  const links = [
      {parent: "flare", children: "analytics"} ,
      {parent: "analytics", children: "cluster"} ,
      {parent: "flare", children: "scale"} ,
      {parent: "analytics", children: "graph"} ,
  ];  

I want to make it into tree, like so:

const tree = {
 "name": "flare",
 "children": [
  {
   "name": "analytics",
   "children": [
    {
     "name": "cluster",
    },
    {
     "name": "graph",
    }
   ]
  }
 ]
};

Here is my attempt:

function buildTree(links) {

    const map = { }

    const findNodeInChildren = (name, obj) => {
      if (obj[name]) {
        return obj
      } else if (!obj.children) {
        return null
      }

      for (let i = 0; i < obj.children.length; i++) {
        const found = findNodeInChildren(name, obj.children[i])
        if (found) return found
      }

      return null
    }
    
    links.forEach(link => {
      const foundNode = findNodeInChildren(link.parent, map)
      
      if (!foundNode) {
        const newNode = {
          name: link.parent,
          children: []
        }
        map[newNode.name] = newNode
      } else {
          foundNode[link.parent].children.push({
          name: link.children,
          children: []
        })
      }
    })

   return map
}

  const links = [
      {parent: "flare", children: "analytics"} ,
      {parent: "analytics", children: "cluster"} ,
      {parent: "flare", children: "scale"} ,
      {parent: "analytics", children: "graph"} ,
  ];  
  
  const tree = buildTree(links)
  const json = JSON.stringify(tree)
  console.log(json)

Here’s the prettified JSON – it’s not working as intended:

{
  "flare": {
    "name": "flare",
    "children": [
      {
        "name": "scale",
        "children": []
      }
    ]
  },
  "analytics": {
    "name": "analytics",
    "children": [
      {
        "name": "graph",
        "children": []
      }
    ]
  }
}

What is going wrong?

I have a button that I want to grow and shrink over and over while the user is mousing over that button

The Codepen linked below is where I currently am stuck.

function startHover(e) {
  btn.classList.add("btnPlaying")
}

function removeHover(e) {
  btn.classList.remove("btnPlaying");
}

const btn = document.querySelector('.btn')
btn.addEventListener("mouseenter", startHover);
btn.addEventListener('transitionend', removeHover);
.btn {
  margin-top: 10rem;
  padding: 20px 100px;
  background-color: rgb(255, 204, 3);
  border-radius: 10px;
  border-style: none;
  box-shadow: 0px 0px 10px black;
  color: blue;
  border: 4px solid rgb(53, 106, 188);
  transition: all 1.07s ease;
}

.btnPlaying {
  transform: scale(1.1);
}
<button class="btn">Play!</button>

https://codepen.io/TerrellsCode/pen/zYEyORB

The button grows and shrinks like intended but only does it one time. Look for any pointers on how to make this grow/shrink animation loop infinitely as long as user is hovering over button. Thank You

How can I display “-” as long as string length in textbox?

I have this list:

let teams = [
“real madrid”,
“barcelona”,
“milan”,
“inter”,
“juventus”,
“manchester united”,
“manchester city”,
“liverpool”,
“arsenal”,
“chelsea”,
“bayern munich”,
];

I wrote code for choose random item from this list but I want display “-” as long as item length.

For example: choose real madrid … I want this – – – – – – – – – – in the text box.

Uploading multiple photos at once in firebase storage and storing their URLs in a firestore document (firebase version 9)

I am building a form where the user needs to input information to create a city document. The user also needs to upload multiple photos of the city. When submitting the form, a new city document is created in firestore, then each photo is uploaded to the associated firebase storage, and finally a new field called photosURLs with all the photos URLs is added to the city document.

Here is my code:

async function addDocument() {
    const docRef = await addDoc(collection(db, "cities"), {
        name: "Tokyo",
        country: "Japan"
      });
    return docRef
}

async function UploadMultiplePhotos(docRef) {
    var photos = []
    for (var i = 0; i < files.value.length; i++) { // files.values contains all the files objects
        const file = files.value[i];
        refStorageFunction(
            storage,
            "cities/" +
            docRef.id +
            "/" +
            file.name
          );
        uploadBytes(storageRef, file).then((snapshot) => {
            getDownloadURL(snapshot.ref).then((downloadURL) => {
                photos.push(downloadURL)
            });
        });
    }
    return Promise.resolve(photos)
}

async function updateDocument(docRef, photos) {
    await updateDoc(docRef, { photosURLs: photos });
}

function createCity() {
    addDocument().then((docRef) => {
        UploadMultiplePhotos(docRef).then((photos) => {
            updateDocument(docRef, photos).then(() => {
                router.push($CITY_PATH)
            })
        })
    })
}

My issue is that the resulting photosURLs field in the city document is empty. It seems my function UploadMultiplePhotos does not wait for the photos array to be completely populated.

How to access Ms Access database from browser in this day and age?

I have an Excel workbook full of macros and Ms Access database to store data. The idea is to have a portable software with minimum dependency of host computer. Developing that is major pain in 2022 AD.

I was planning on rewriting it for web UI to drop one dependency, but it would still need to use Ms Access (security and backwards compatibility).

Is there anyway to access the Access with javascript? I find references to now-buried ActiveX components and ODBC settings on Windows, but is that all there is? No workarounds that would enable modern UI for Access on a local computer?

What alternatives do I have should I consider different database engine? The requirements are simple: it needs to run when opening “mysheets.html” from local hard drive to a browser, have no dependencies to configuration of host computer, needs to be able to travel on usb-stick and have password protection for data (any is better than none). It’s acceptable to make it interop with local exe-files (that can travel with), if possbile.

I would rather not use Node for this, but looks like it’s one option (trading a dependency to another). Nothing that needs to be built and does not make source code “available” in the application does not work, the source code cannot be lost under any circumstances (high mobility).

Using Underscore.js help to iterate over it

So I managed to get my array grouped by Entity name using Underscore.js with _.groupBy. It gives me the next output:

enter image description here

The output its correct, the problem is that I cant *ngfor over it on my html because is obviously not an array. Do anybody know how to iterate over this and for example show on my html part a “mat-expansion-panel-header” with the output blue text?

Creating to and from range values, count’s don’t match up

can’t figure out the correct calculation for this. So basically I have got some ranges returned from an API (items) and a count of vehicles within that range. I want to have the correct numbers within the dropdowns, so for example selecting from 2000 would return all the vehicles, as that’s the lowest price, however it says 27.

Then going further down that from list it becomes more and more off, as the total vehicles should match, and total vehicles will be correct.

Made the best example I could to show you the issue.

new Vue({
  data: {
    items: [
        { value: { from: 2000, to: 2500 }, count: 1 },
        { value: { from: 2500, to: 3000 }, count: 0 },
        { value: { from: 3000, to: 3500 }, count: 0 },
        { value: { from: 3500, to: 4000 }, count: 1 },
        { value: { from: 4000, to: 4500 }, count: 2 },
        { value: { from: 4500, to: 5000 }, count: 2 },
        { value: { from: 5000, to: 5500 }, count: 0 },
        { value: { from: 5500, to: 6000 }, count: 2 },
        { value: { from: 6000, to: 6500 }, count: 0 },
        { value: { from: 6500, to: 7000 }, count: 0 },
        { value: { from: 7000, to: 7500 }, count: 0 },
        { value: { from: 7500, to: 8000 }, count: 2 },
        { value: { from: 8000, to: 8500 }, count: 0 },
        { value: { from: 8500, to: 9000 }, count: 1 },
        { value: { from: 9000, to: 9500 }, count: 0 },
        { value: { from: 9500, to: 10000 }, count: 0 },
        { value: { from: 10000, to: 11000 }, count: 0 },
        { value: { from: 11000, to: 12000 }, count: 1 },
        { value: { from: 12000, to: 13000 }, count: 0 },
        { value: { from: 13000, to: 14000 }, count: 0 },
        { value: { from: 14000, to: 15000 }, count: 2 },
        { value: { from: 15000, to: 20000 }, count: 7 },
        { value: { from: 20000, to: 25000 }, count: 3 },
        { value: { from: 25000, to: 30000 }, count: 2 },
        { value: { from: 30000, to: 40000 }, count: 1 },
        { value: { from: 40000, to: 50000 }, count: 1 },
        { value: { from: 50000, to: 60000 }, count: 0 }
    ],
    selected: {
      from: null,
      to: null
    }
  },
  computed: {
    total() {
      let totalVehicles = 0;
      this.items.forEach(item => {
        const greaterThan = !this.selected.from || (item.value.from >= this.selected.from);
        const lessThan = !this.selected.to || (item.value.to < this.selected.to);
        if (greaterThan && lessThan) {
          totalVehicles += item.count;
        }
      });
      return totalVehicles;
    },
    rangeValues() {

      const dropdown = {
          from: [], to: []
      };

      // To
      let counter = 0;
      dropdown.to = this.items.map(i => {
          counter += i.count;
          return { value: i.value.to, label: i.value.to, count: counter }
      }).filter(Boolean);

      // From
      counter = dropdown.to[dropdown.to.length-1].count;
      dropdown.from = this.items.map(i => {
          if (this.selected.to && i.value.from >= this.selected.to) {
              return null;
          }
          counter -= i.count;
          return { value: i.value.from, label: i.value.from, count: counter }
      }).filter(Boolean);

      return dropdown;
    }
  }
}).$mount('#app')
h3, p {
  margin: 0;
}
p {
  margin-bottom: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h3>Total Vehicles ({{ total }})</h3>
  <p>The above in reality is what is returned from the API</p>
  <label for="from">
    From
    <select name="from" id="from" v-model="selected.from">
      <option :value="null">Select From</option>
      <option :value="item.value"
              v-for="item in rangeValues.from"
              :key=`from-${item.value}`>{{ item.label }} ({{ item.count }})</option>
    </select>
  </label>
  <label for="to">
    To
    <select name="to" id="to" v-model="selected.to">
      <option :value="null">Select To</option>
      <option :value="item.value"
              v-for="item in rangeValues.to"
              :key=`to-${item.value}`>{{ item.label }} ({{ item.count }})</option>
    </select>
  </label>
</div>

Hooks dont update the states correctly

Hi im trying to setting states in react but they dont update correctly, i have:

const [campusName, setCampusName] = useState("");
const [assists, setAssists] = useState({
    name:"",
    campusid: "",
    hour: "",
    day: "",
    month: "",
    year: "",
    studentid: "",
});

const [date, setDate] = useState({
    day: "",
    month: "",
    year: "",
    hour: "",
});

useEffect(()=>{
getData();
}, [])

const getData = async() =>{

    //campus name
    const campusResponse = await fetch("http://localhost:2000/info/campus/"+params.campusid);
    const campusData = await campusResponse.json();
    setCampusName(campusData.name);

    //date
    const date = new Date();   

    setDate({
        day: date.getDate(),
    month: date.getMonth()+1,
    year: date.getFullYear(),
    hour: `${date.getHours()}:${date.getMinutes()}`,
    });

    setAssists();
}

const settingAssistence = () => {
    setAsists({
        name: campusName,
        campusid: params.campusid,
        hour: date.hour,
        day: date.day,
        month: date.month,
        year: date.year,
        studentid: params.studentid,
    })

    console.log("result", asissts);
}

the console.log prints the assists object empty, but if i refresh the page 3 times it works, how can i set the states correctly? the fetch with http://localhost:2000/info/campus/ also works good and give me the correct data, but when i set it into the hook is not updating correctly.

Expo app crashes on andriod emulator when using navigation stack

I just entered react native about a week ago and I just stumbled on this problem.

Every time I connect the navigation stack/drawer to my home app.js and then I run the expo app it shutdowns unexpectedly. Sometimes it shows an error but for less than a second then closes. But most times it never shows an error before closing.

I was able to capture an error but I’m not sure if it was the error that briefly shows. This was the error

unexpected identifier 'n'. Expected either in or if in enumeration syntax.

I have no idea where this error comes from.

My App.js

    import Home from './screens/Home';
// import * as Font from 'expo-font';
import AppLoading from 'expo-app-loading'
import { useFonts } from 'expo-font';
import React,{ useState } from 'react';
import Navigator from './routes/HomeStack'

export default function App() {
  const [fontLoaded] = useFonts({
    'nunitoBold': require('./assets/fonts/Nunito-Bold.ttf'),
    'nunitoRegular': require('./assets/fonts/Nunito-Regular.ttf'),
  })
    // const [fontLoaded,setFontLoaded] = useState(false)

    if (!fontLoaded) {
      return (
        <AppLoading/>
      )
    }else{
      return (
        <Home/>
      )
    }
}

My HomeStack.js

import { createStackNavigator } from "react-navigation-stack";
import { createAppContainer } from "react-navigation";
import Details from "../screens/Details";
import Home from "../screens/Home";

const screens = {
    Home: {
        screen: Home,
    },
    ReviewDetails: {
        screen: Details,
    },
}

const HomeStack = createStackNavigator(screens, {
    defaultNavigationOptions: {
       headerStyle:{ backgroundColor: '#f00' },
       headerTintColor: '#444'
    }
})

export default createAppContainer(HomeStack);

My Home.js

import React, { useState } from 'react'
import { FlatList, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { globalStyles } from '../styles/global';

export default function Home({ navigation }) {
  const [reviews, setReviews] = useState([
    { title: 'Zelda, Breath of Fresh Air', rating: 5, body: 'lorem ipsum', key: '1' },
    { title: 'Gotta Catch Them All (again)', rating: 4, body: 'lorem ipsum', key: '2' },
    { title: 'Not So "Final" Fantasy', rating: 3, body: 'lorem ipsum', key: '3' },
  ]);
  return (
    <View style={globalStyles.container}>
      <FlatList 
        data={reviews}
        renderItem={({ item }) => (
          <TouchableOpacity onPress={() => navigation.navigate('ReviewDetails', item)}>
            <Text>{item.title}</Text>
          </TouchableOpacity>
        )}
      />
    </View>
  );
}

Also this worked yesterday perfectly. I just started receiving such errors just today and I hadn’t even touched my code.

My package.json

{
  "name": "gamezone",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "@react-navigation/native": "^6.0.6",
    "@react-navigation/native-stack": "^6.2.5",
    "expo": "~44.0.0",
    "expo-app-loading": "~1.3.0",
    "expo-font": "~10.0.4",
    "expo-status-bar": "~1.2.0",
    "react": "17.0.1",
    "react-dom": "17.0.1",
    "react-native": "0.64.3",
    "react-native-safe-area-context": "3.3.2",
    "react-native-screens": "~3.10.1",
    "react-native-web": "0.17.1",
    "react-navigation": "^4.4.4",
    "react-navigation-drawer": "^2.7.1",
    "react-navigation-stack": "^2.10.4"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9"
  },
  "private": true
}

Finding a unique word in string with Javascript

I am trying to find a unique word in my input string with JS and have written a code. However, my code doesn’t work and I don’t know why. Could anyone help me please?

function findUniqueWord(index){
    var show = []
    var result = [...index]
    for (let i = 0; i < result.length; i++) {
        for (let j = i + 1; j < result.length; j++) {
            if(result[i] === result[j]){
                
            }
            else{
                return show.push(result[i])
            }
            
        } 
    }
    return show
}

console.log(findUniqueWord('A2A'));

How do webdevelopers create “background search” websites that appear to be running a long difficult search?

There are a number of paywall websites that are designed to allow the user to find out public record information about individuals. When the user enters some basic information about the individual and submits the search, a status bar appears and the websites begins flipping through blurred out photos, to signify that a large search is being executed.

How to build a regex match for these keywords?

I’m trying to build a regex that would detect a group of keywords in an sentence.

For ex: I want to detect need a team or need a hand in these two sentences

  • I need a team to help me with my homework
  • They are going to need a hand to fix that door

I have something like this: /(need a team) | (need a hand)/gmi but it does not work.
Thank you