Calculate average of an array with objects that has a nested Object

I am trying to loop through array of Objects and calculate the average of a nested Object containing several different keys.
This is the start array:

[{
  course: "math",
  id: 4,
  values: {
    2017: 8,
    2018: 9
  }
}, {
  course: "math",
  id: 4,
  values: {
    2017: 5,
    2019: 7
  }
}]

This is my goal:

{2017:6.5,2018:9,2019:7}

Now it returns correct for 2017 but NaN for 2018 and 2019. If anyone have better way of solving this that doesn’t require so much please provide to.

This is what I have tried so far. I have been searching a lot but not really found anything I can use.

const testObject = [{
    id: 4,
    course: "math",
    values: {
      2017: 8,
      2018: 9
    }
  },
  {
    id: 5,
    course: "English",
    values: {
      2017: 8,
      2018: 9
    }
  },
  {
    id: 4,
    course: "math",
    values: {
      2017: 5,
      2019: 7
    }
  },
  {
    id: 4,
    course: "english",
    values: {
      2017: 5,
      2019: 7
    }
  },
]
//First I filter out the id 4 and course Math
const mathid1 = testObject.filter((e) => e.id === 4 && e.course === "math");
//I than find all the different years
const ArrayOfAllYears = []
mathid1.map((element) => {
  ArrayOfAllYears.push(Object.keys(element.values));
})
//I here find all the different years
const withDuplicates = ArrayOfAllYears.reduce(function(arrayOne, arrayTwo){
    return arrayOne.concat(arrayTwo);
}, []);

const withoutDuplicates = Array.from(new Set(withDuplicates));
//Here I just create the calculate average function
const Result = {}
const calculateAverage = (array) => {
  const sum = array.reduce((a, b) => a + b);
  return sum / array.length;
};
const newObj = {}
withoutDuplicates.map((year) => {
  let reformattedArray = mathid1.map(obj => {
  if(obj["values"][year]){
    return obj["values"][year]
    }
  })
  newObj[year] = calculateAverage(reformattedArray)
})
console.log(newObj)
// I want to calculate the average of the mathid1 values and return it on a Object like {2017:..,2018..}

SVG element bounding box changes on transform

As I understand it, getBBox() is supposed to ignore the transformations applied to the element it’s measuring.

eg: if I have: <g transform="scale(0.5, 0.5)"><rect width="100" height="100" /></g>, calling getBBox on <g> will always return width: 100, height: 100, no matter what the scale() args are. However, this does NOT appear to be the case when using a <text> element instead of <rect>. The size of <text> reported by getBBox() changes as the transformation changes.

Full example:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <svg width="500" height="500">

    <g>
      <text>Text goes here</text>
    </g>
  </svg>

  <script>
    const gNode = document.querySelector("g");

    const dimensionsBB = () => {
      console.log(gNode.getBBox());
    }

    // trigger every time a change in size is detected
    const resizeObserver = new ResizeObserver(dimensionsBB);

    resizeObserver.observe(gNode);

    // update transformation every second
    setInterval(() => {
      gNode.setAttribute("transform", `scale(${Math.random()}, ${Math.random()})`);
    }, 1000);
  </script>
</body>
</html>

In this example, the resizeObserver is triggered each time the scale changes, and the dimensions reported by getBBox() are different each time (with slight variations).

Why? And is there a way to always get a consistent result?

Screen Recording Portion of Screen with JavaScript

I am attempting to implement a screen recorder in JavaScript that records a video feed rather than the entire screen. My question is whether or not this is possible using getDisplayMedia or if there is a library to achieve this. This is my current implementation, which will ask and record the entire screen.

const handleRecord = async () => {
    // console.log('record')
    let stream = await navigator.mediaDevices.getDisplayMedia({
      video: true
    })
    // Needed for better browser support 
    const mime = MediaRecorder.isTypeSupported("video/webm; codecs=vp9")
      ? "video/webm; codecs=vp9"
      : "video/webm"

    let mediaRecorder = new MediaRecorder(stream, { mimeType: mime })

    let chunks = []
    mediaRecorder.addEventListener('dataavailable', ({ data }) => chunks.push(data))

    mediaRecorder.addEventListener('stop', function () {
      let blob = new Blob(chunks, {type: chunks[0].type})
      let url = URL.createObjectURL(blob)
      let video = document.querySelector("#cameraFeed")
      video.src = url

      let a = document.createElement('a')
      a.href = url
      a.download = 'video.webm'
      a.click()
    })

    //we have to start the recorder manually
    mediaRecorder.start()
  }

How to take the result of two randomly generated values from two functions and add them together?

Both the first and second functions (n1 and n2) output a random number from their respective arrays into the console. Issues arise when I try to add these two generated values together and have the result displayed in the console as well. I tried creating a global variable to add the results but it did not work.

If n1() outputs 3 and n2() outputs 1, I would like the console to output 4.

Here is my code:

var add = (n1() + n2());

    function n1() {

    var cpuSelection =  [1, 2, 3];
    
    var randomSelection = cpuSelection[Math.floor(Math.random() * cpuSelection.length)];
    
    console.log(randomSelection)
    
    
    }
    
    n1();

    function n2() {

        var cpuSelection =  [1, 2, 3];
        
        var randomSelection = cpuSelection[Math.floor(Math.random() * cpuSelection.length)];
        
        console.log(randomSelection)
        
        
        }
        
        n2();

    
    console.log(add)

React js ecommerce price change when size and material variants option selected

I am trying to get the final price in the productInfo page when the material and size variants options are selected.
In the data.js:

export const productItems = [
    {
        id: 1,
        image: ["../Images/Prod1/Swiming_fish_W.png","../Images/Prod1/Ocean Fish2.png"],
        title: "Swim Fish",
        price:49.99,
        desc: "Simplicty, Naturality, and Humanity of Art",
        variants: [{material: "Stretched Canvas", size: "12x16 inches", price: 49},
                   {material: "Stretched Canvas", size: "15x20 inches",  price: 69},
                   {material: "Fine Art Print", size: "12x16 inches",  price:39},
                   {material: "Fine Art Print", size: "15x20 inches",  price: 59},
                  ],
        
    },

    {
        id: 2,
        image: ["../Images/Prod2/Duckling_W.png","../Images/Prod2/Duckling 2.png"],
        title: "Bath Duckling",
        price:49.99,
        desc: "Simplicty, Naturality, and Humanity of Art",
        variants: [{material: "Stretched Canvas",size: "20x24 inches",  price: 69},
                   {material: "Stretched Canvas",size: "24x30 inches",  price: 79},
                   {material: "Fine Art Print", size: "20x24 inches",  price:59},
                   {material: "Fine Art Print", size: "24x30 inches",  price: 69},
                   ],
    }]

In the detailProductPage.js

import React, { useEffect, useState } from 'react';
// import { Col, Row } from 'antd';
import ProductImages from './ProductImages';
import ProductInfo from './ProductInfo';
import {productItems} from '../Data';
import { useParams } from 'react-router-dom';
import './DetailProductPage.css';


function DetailProductPage() {

    const { id }=useParams();
    const [details, setDetails]=useState([])
    
    useEffect(() => {
        setDetails(productItems.find(item => String(item.id) ===id ))
    
     }, [id]);
        
    return (
        <div className="postPage" style={{width:'100%', padding: '5rem 3rem'}}>

        <div className="detailInfo">
          <div className="detailLeft">
               <ProductImages detail={details} />
           </div>

           <div className="detailRight">
               <ProductInfo  detail={details} />
           </div>
        </div>
      </div>
  )
}

export default DetailProductPage

Finally in the ProductInfo.js

import React, {useEffect, useState} from 'react';
import { useStateValue } from '../StateProvider';
import './ProductInfo.css';
import Select from 'react-select';


function ProductInfo(props) {
  const [Product, setProduct] = useState({})
  const [{basket},dispatch]=useStateValue()

  const [size, setSize] = React.useState();
  const [material, setMaterial] = React.useState();
  const [price, setPrice] = React.useState();
  console.log(props.detail.variants)

  const materialOptions = props.detail.variants
    .map((p) => p.material)
    .filter((v, i, a) => a.indexOf(v) === i)
    .map((material) => ({ label: material, value: material }))
  console.log(materialOptions)

  const sizeOptions = props.detail.variants
    .map((p) => p.size)
    .filter((v, i, a) => a.indexOf(v) === i)
    .map((size) => ({ label: size, value: size }));
  console.log(sizeOptions)
  
  const priceOptions = props.detail.variants
    .filter((p) => size && p.size === size.value && material && p.material=== material.value)
    .map((p) => p.price)
    .filter((v, i, a) => a.indexOf(v) === i)
    .map((price) => ({ label: price, value: price }));
  console.log(priceOptions.length)

    useEffect(()=>{
        setProduct(props.detail)
      }, [props.detail])
    
return (
   <div className='prod__info'>
        
    <h1>{Product.title}</h1>
    <h5 className='prod__desc'>Description</h5>
    <p className='prod__text'>{Product.desc}</p>

    <p className='prod__price'>
            <small>$</small>
            if (priceOptions.length===1){
              priceOptions.value
            } else {Product.price} 
    </p>
    <br />
      <p className='prod__desc'>Material</p>
      <div style={{boxShadow: '0 5px 5px #939596',cursor:'pointer',borderRadius: '10px!'}}>
      <Select value={material} onChange={setMaterial} options={materialOptions} />
      </div>

      <p className='prod__desc'>Size</p>
      <div style={{boxShadow: '0 5px 5px #939596',cursor:'pointer',borderRadius: '10px!'}}>
      <Select value={size} onChange={setSize} options={sizeOptions} />
      
    </div>
    <br />
    <br />
    <div className='button__cart'>    
      <button className='prod__button'
          onClick={addToBasket}
        >
            Add to basket
    </button>
    </div>

</div>

)
}

export default ProductInfo

I have problems in getting the final price change after material and size variant options selected in ProductInfo.js

<p className='prod__price'>
            <small>$</small>
            if (priceOptions.length===1){
              priceOptions.value
            } else {Product.price} 
    </p>

For reference, my website is weiwhite.com, clicking on one of the painting for the product detail page.

How do you get the intersection of objects that are the same in an array of multiple array of objects?

Using Javascript, how do you get the intersection of objects that are the same in an array of multiple array of objects, where if the value of the first key is the same, it also checks the value of the second key?

start:

all = [
  [
    {
      slug: "food",
      name: "burger"
    },
    {
      slug: "food",
      name: "pizza"
    }
  ],
  [
    {
      slug: "food",
      name: "burger"
    },
    {
      slug: "food",
      name: "pizza"
    }
    {
      slug: "drink",
      name: "soda"
    }
  ],
  [
    {
      slug: "food",
      name: "burger"
    },
    {
      slug: "food",
      name: "pizza"
    },
    {
      slug: "drink",
      name: "water"
    }
  ],
]

goal:

intersection = [
  {
    slug: "food",
    name: "burger"
  },
  {
    slug: "food",
    name: "pizza"
  }
]

API DELETE method issue

I have an issue with my javaScript code as the delete feature is working but, it is not deleting the right data …
Example:
1 – test1
2 – test2
3 – test3

My issue is when I try to delete test1, the program deletes test3 which means the program always deletes the last data in the list.

Please, could you help?

Here’s my code:

const url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/2877332";
let theTask = [];
let text = '';
const init = () => {
    document.querySelector("#newTask").addEventListener("click", addNewTask);
    addNewTask();
    getDataa();
};
const addNewTask = () => {
    console.log("Adding a new task...");
    let xhr = new XMLHttpRequest();
    let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks";
    let apiKey = "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S";
    let studentId = "2877332";
    let taskDescription = document.querySelector("#task").value;
    let theTask = taskDescription;

    let params = {
        StudentId: studentId,
        Description: taskDescription
    };
    xhr.open("post", url);

    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("x-api-key", apiKey);
    xhr.onreadystatechange = () => {
        if (xhr.readyState == 4) {
        }
    }
    xhr.send(JSON.stringify(params));
    getDataa();
};
const getDataa = () => {
    console.log("get Data")
    fetch(url, {
            method: "GET",
            withCredentials: true,
            headers: {
                "x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
                "Content-Type": "application/json"
            }
        })
        .then(resp => resp.json())
        .then(function(data) {
            console.log(data);
            // Loop to access all rows
            for (i = 0; i <= data.ScannedCount; i++) {

                let text = '';
                //const items = data.Items[i].Description;
                Array.from(data.Items).forEach(myFunction);
                // display the data to the end user and link it to the index page
                document.getElementById("displayTable").innerHTML = text;

                function myFunction(item, index) {

                    theTask= data.Items[index].Description;
                    text += ' <button type="button" class="btn" id="task2" onclick="deleteData()"> <i class="fa fa-trash"></i> </button> '+ "  " + data.Items[index].Description +   "<br>";
                }
            }

        })
        .catch(function(error) {
            console.log(error);
        });
}
async function deleteData() {
    console.log("deleteing data");

    let xhr = new XMLHttpRequest();
    let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/";
    let studentId = "2877332";
    let taskDescription = theTask;
    fetch(url, {
            method: 'DELETE',

            headers: {
                "Content-Type": "application/json",
                "x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
            },

            body: JSON.stringify({
                'StudentId': studentId,
                'Description': taskDescription,
                'version': 'JSON',
            }),
        })
        .then(res => res.json()).then(console.log);
        console.log(taskDescription);
        getDataa();
}
window.onload = init;

While Loop freezes page in React

Not sure if I’m missing something here, but a very simple while loop is freezing the page.

Checked:

Console logged inside useEffect to check if component re-rendering
unusually, but that’s not the case.

function IterationComponent() {

    const [c1, incrementC1] = useState(() => 0);
    const [c2, incrementC2] = useState(() => 0);

    useEffect(() => {
        console.log(1)
    }); 

    function incrementC1Fn () {
        incrementC1(prevValue => prevValue + 1)
    }

    function incrementC2Fn () {
        incrementC2(prevValue => prevValue + 1)
    }

    const isEven = () => {
        let i = 0;
        while(i < 2); i++
        return c1 % 2 === 0;
    }

    return (
        <>
            <button onClick={incrementC1Fn}>C1 - {c1}</button>
            <button onClick={incrementC2Fn}>C2 - {c2}</button>
            <span>{isEven() ? 'Even' : 'Odd'}</span>
        </>
    
    )
}

Whenever I’m adding the while loop inside isEven function, then the page freezes as I’m not able to click any button

NOTE: Please don’t ask me why I am doing something like this or what’s the purpose of this or I can do this in some other way to increase the performance.
This is just for my understanding as I want to deliberately make the isEven function works slowly. It’s just for educational purpose. But I think this simple while loop shouldn’t freeze the page unless I’m doing something wrong here.

React Native app needs to restart for AsyncStorage to work

I am currently working on a React Native app that uses AsyncStorage to store authentications tokens for users. I have a context to do this:

import React, { useReducer, createContext } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import jwtDecode from "jwt-decode";

const initialState = {
  user: null,
};

AsyncStorage.getItem("user").then((res) => {
  if (res !== null || res !== undefined) {
    initialState.user = jwtDecode(res);
  } else return;
});

const AuthContext = createContext({
  user: null,
  login: (userData) => {},
  logout: () => {},
});

function authReducer(state, action) {
  switch (action.type) {
    case "LOGIN":
      return {
        ...state,
        user: action.payload,
      };
    case "LOGOUT":
      return {
        ...state,
        user: null,
      };

    default:
      return state;
  }
}

function AuthProvider(props) {
  const [state, dispatch] = useReducer(authReducer, initialState);

  function login(userData) {
    AsyncStorage.setItem("user", userData.token);
    dispatch({
      type: "LOGIN",
      payload: userData,
    });
  }

  function logout() {
    AsyncStorage.clear();
    dispatch({ type: "LOGOUT" });
  }

  return (
    <AuthContext.Provider
      value={{ user: state.user, login, logout }}
      {...props}
    />
  );
}

export { AuthContext, AuthProvider };

My login function looks like this:

const [login, { error: loginError }] = useMutation(LOGIN_USER, {
    update(_, { data: { login: userData } }) {
      context.login(userData);
      colorContext.setColor(
        String(
          _palette__colors[
            Math.ceil(Math.random() * _palette__colors.length - 1)
          ]
        )
      );
      navigation.reset({
        index: 0,
        routes: [{ name: "BottomTab" }],
      });
    },
    variables: {
      email,
      password,
    },
  });

However, when I try to login the app returns and error saying that my “user” object is undefined. When I restart the app everything works fine, so it seems as if AsyncStorage needs to manually reload in order to load the data or something. Anyone knows how to resolve this error?

Angular service with providedIn: ‘root’ is an empty object

I just created a brand new service inside an angular application and use providedIn: ‘root’ to make it available anywhere in the application.

But when I import it and try to use it says its methods are undefined.

Here is the code

service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class Service {
  public publicMethod() {}
}

component.ts

import { Service } from 'path/to/service';
import { Component } from '@angular/core';
import { AccountService } from 'app/core';
@Component({
    selector: 'footer',
    templateUrl: './footer.component.html',
})
export class FooterComponent {
  constructor(private readonly service: Service) {
     this.service.publicMethod // undefined
  }
}

Other services imported the same way are working fine.
What can cause this issue?

How do I control which elements are visible depending on screen size in Material UI?

for context I want to have 2 divs if screen size is bigger than a phone screen, and 1 div if screen is small enough. Using material ui here how I attempted this:

<Grid container spacing={2}>
        <Grid item sx={{ display: {xs: 'none', sm: 'none', md: [12]}}} className='x1'>
            <TopLeft/>
        </Grid>

        <Grid item sx={{ display: {xs: 'none', sm: 'none', md: [12]}}} className='x2'>
            <TopRight/>
        </Grid>

        <Grid item sx={{ display: {xs: [12], sm: 'none', md: 'none'}}} className='x2'>
            <Top/>
        </Grid>

        <Grid item sx={{ display: {xs: '12'}}} className='x3'>
            <Bottom/>
        </Grid>
    </Grid>

My understanding was I could set the width for breakpoint sizes. So what I would want to do is have 2 divs displayed for sizes larger than ‘xs’, and for small screen sizes the top two divs would have display property as none, while the 3rd div would now have a width of 12 columns

Please let me know if I can provide more info

How to place a second marker 10km north of original marker?

so this is my code. In the first eventListener I place a marker anywhere on my map. However, when I either ‘dblclick’ or ‘mouseOver’ the marker I want it to place another marker 10km north of the first/original marker.

function placeMarker(position, map){
    var marker = new google.maps.Marker({
        position: position,
        map: map
    });
    array.push(position);
}



function button(){
    var point;
    var pointLat;
    var pointLng;
    var a = map.addListener('click', function(e){
        point = e.latLng;
        placeMarker(e.latLng, map);
        map.panTo(point);
        pointLat = map.center.lat() + 0.179664;
        pointLng = map.center.lng();
        
    });
    
    var newPoint = (pointLat, pointLng);
    map.addListener(a,'dblclick', function(){
        placeMarker(newPoint, map);
    });
    
}

Preventing form from going to action page also prevents data from being submitted (jQuery)

I created a form that submits its input to a database via a PHP page, and it works great, except for that I can’t get the below script to work.

The intention is to submit the form but without actually jumping to createaccount.php. However, when I use the jQuery script below it prevents the form data from being submitted at all.
This code is from a project from a few years ago, and back then it worked fine. It seems it also works for everyone else on StackOverflow, so… confusing.

If it helps, I’m using Chrome. And I also tried using e instead of event, and instead of preventDefault() I also tried stopPropagation() and stopImmediatePropagation(), but these have the same results. Any ideas would be appreciated. Thanks for your time!

HTML

<form action="createaccount.php" method="post" id="form">
  Username:<input type="text" name="username">
  Password:<input type="password" name="password">
  Email:<input type="email" name="email">
  <input type="submit" name="submit" value="Submit">
</form>

JavaScript (jQuery)

$(document).ready(function() {
  $("#form").on('submit', function(event){
     event.preventDefault();
  });
})

Avoid undefined while nseted destructuring JS

I can’t find a solution here for my specific case.
Response from API in which target, title & url while destructuring ‘home_3_button’ can be undefined, so I’m trying to handle it. Is it even possible?

 const [{home_3_subtitle, home_3_text, home_3_pros, home_3_button: {target, title, url}}] = pageData;

Thanks in advance!