Pino-tee logs twice on other logs

References: https://github.com/pinojs/pino-tee

I have two logs, info.log and error.log
but the thing is, when I go to info.log, the log for error.log is there

So technically, What I have is :

error.log -> ERROR 1 (W/C correct)

info.log -> ERROR 1, INFO 1 (The error log is there)

What I want is that they go to seperate logs appropriately.

Heres the code from references link above:

const pinoms = require("pino-multi-stream");
const childProcess = require("child_process");
const stream = require("stream");

const cwd = process.cwd();
const { env } = process;

const logThrough = new stream.PassThrough();
const prettyStream = pinoms.prettyStream();
const streams = [{ stream: logThrough }, { stream: prettyStream }];
const log = pinoms(pinoms.multistream(streams));

const child = childProcess.spawn(
  process.execPath,
  [
    require.resolve("pino-tee"),
    "info",
    `${__dirname}/info`,
    "error",
    `${__dirname}/error`,
  ],
  { cwd, env }
);

logThrough.pipe(child.stdin);

module.exports = log;

Logging test on other file:

const logger = require("./Common/logger");
logger.info("INFO 1");
logger.error("ERROR 1");

Result:

info.log

{"level":30,"time":1651894649071,"pid":19380,"hostname":"","msg":"INFO 1"}
{"level":50,"time":1651894649074,"pid":19380,"hostname":"","msg":"ERROR 1"}

error.log

{"level":50,"time":1651894649074,"pid":19380,"hostname":"","msg":"ERROR 1"}

Static builds of react js giving error for array.map but developmemnt server is running well

The error is in the functionality where the frontend requests for data from the backend and then uses array.map to display each element of the data. The data is in Array format that is checked.

Running the frontend with npm start and backend separately is giving no error. But when I try to build the static file using npm run build and serve those files, then I am getting react-dom.production.min.js:186 TypeError: r.map is not a function.

I think my problem is similar to Unable to use Array map function in React static build / works using dev server but the last comment says the problem isn’t solved yet.

Here is the repo of my code https://github.com/somesh-banerjee/Map-points/tree/test-deploy

The exact error message

react-dom.production.min.js:186 TypeError: r.map is not a function
    at Po (App.js:92:21)
    at gi (react-dom.production.min.js:166:137)
    at El (react-dom.production.min.js:214:217)
    at du (react-dom.production.min.js:291:202)
    at us (react-dom.production.min.js:279:379)
    at is (react-dom.production.min.js:279:310)
    at as (react-dom.production.min.js:279:170)
    at Gu (react-dom.production.min.js:270:443)
    at Qu (react-dom.production.min.js:268:421)
    at S (scheduler.production.min.js:13:203)
rl @ react-dom.production.min.js:186
n.callback @ react-dom.production.min.js:186
la @ react-dom.production.min.js:137
su @ react-dom.production.min.js:261
uu @ react-dom.production.min.js:259
lu @ react-dom.production.min.js:258
(anonymous) @ react-dom.production.min.js:282
cs @ react-dom.production.min.js:280
Qu @ react-dom.production.min.js:270
S @ scheduler.production.min.js:13
N @ scheduler.production.min.js:14

App.js:92 Uncaught TypeError: r.map is not a function
    at Po (App.js:92:21)
    at gi (react-dom.production.min.js:166:137)
    at El (react-dom.production.min.js:214:217)
    at du (react-dom.production.min.js:291:202)
    at us (react-dom.production.min.js:279:379)
    at is (react-dom.production.min.js:279:310)
    at as (react-dom.production.min.js:279:170)
    at Gu (react-dom.production.min.js:270:443)
    at Qu (react-dom.production.min.js:268:421)
    at S (scheduler.production.min.js:13:203)
Po @ App.js:92
gi @ react-dom.production.min.js:166
El @ react-dom.production.min.js:214
du @ react-dom.production.min.js:291
us @ react-dom.production.min.js:279
is @ react-dom.production.min.js:279
as @ react-dom.production.min.js:279
Gu @ react-dom.production.min.js:270
Qu @ react-dom.production.min.js:268
S @ scheduler.production.min.js:13
N @ scheduler.production.min.js:14

App.js code(Error at line 92)

import { useEffect, useState } from 'react';
import Map,{ Marker,Popup } from 'react-map-gl';
import { Star,Room } from '@material-ui/icons';
import './app.css';
import axios from 'axios';
import Register from './components/Register';
import Login from './components/Login';
//import { format } from 'timeago.js';

function App() {
  const myStorage = window.localStorage
  const [pins,setPins] = useState([]);
  const [currentPlaceId, setCurrentPlaceId] = useState(null);
  const [currentUsername, setCurrentUsername] = useState(myStorage.getItem('user'));
  const [newPlace, setNewPlace] = useState(null);
  const [title, setTitle] = useState(null);
  const [review, setReview] = useState(null);
  const [rating, setRating] = useState(0);
  const [showRegister, setShowRegister] = useState(false);
  const [showLogin, setShowLogin] = useState(false);
  const [viewState, setViewState] =   useState({
    latitude: 22.572645,
    longitude: 88.363892,
    zoom: 8
  });

  useEffect(()=>{
    const getPins = async() =>{
      try {
        const res = await axios.get("/pins");
        // console.log(res.data)
        setPins(res.data);
      } catch (err) {
        console.log(err)
      }
    }
    getPins();
  },[])

  const handleMarkerClick = (id,lat,long) =>{
    setCurrentPlaceId(id)
    setViewState({
      ...viewState,
      latitude: lat,
      longitude: long,
    })
  }

  const handleAddPlace = (e) =>{
    setNewPlace({
      long: e.lngLat.lng,
      lat: e.lngLat.lat,
    })
  }

  const handleSubmit = async(e) =>{
    e.preventDefault();
    const newPin = {
      username: currentUsername,
      title,
      desc: review,
      rating,
      lat: newPlace.lat,
      long: newPlace.long,
    }

    try {
      const res = await axios.post("/pins",newPin)
      setPins([...pins, res.data])
      setNewPlace(null)
    } catch (e) {
      console.log(e)
    }
  }

  const handleLogout = async() => {
    myStorage.removeItem('user')
    setCurrentUsername(null)
  }

  return (
    <div className="App">
      <Map
      {...viewState}
      onMove={evt => setViewState(evt.viewState)}
      style={{width: "100vw", height: "100vh"}}
      mapStyle="mapbox://styles/mapbox/streets-v9"
      mapboxAccessToken={process.env.REACT_APP_MAPBOX}
      onDblClick = {handleAddPlace}
      // transitionDuration="200"
    >
      {pins && pins.map(p=>(
          <div key={p._id}>
          <Marker
            longitude={p.long}
            latitude={p.lat}
            color="red">
              <Room
                style={{
                  fontSize: 7 * viewState.zoom,
                  color:
                    currentUsername === p.username ? "blue" : "green",
                  cursor: "pointer",
                }}
                onClick={() => handleMarkerClick(p._id, p.lat, p.long)}    
              />
          </Marker>
          {p._id === currentPlaceId && (
              <Popup
                longitude={p.long}
                latitude={p.lat}
                closeOnClick={false}
                onClose={() => setCurrentPlaceId(null)}
                anchor="left">
                <div className='card'>
                  <label>Place</label>
                  <h4 className='place'>{p.title}</h4>
                  <label>Review</label>
                  <p>{p.desc}</p>
                  <label>Rating</label>
                  <div className='stars'>
                    {Array(p.rating).fill(<Star />)}
                  </div>
                  <label>Information</label>
                  <span className='username'>Created by {p.username}</span>
                  <span className='date'>{/*format(p.createdAt)*/}</span>

                </div>
              </Popup>
            )
          }
          </div>
        ))
      }
      {newPlace && (
        <Popup
          longitude={newPlace.long}
          latitude={newPlace.lat}
          closeOnClick={false}
          onClose={() => setNewPlace(null)}
          anchor="left">
          <div>
            <form onSubmit={handleSubmit}>
              <label>Title</label>
              <input onChange={(e)=>setTitle(e.target.value)} />
              <label>Review</label>
              <textarea onChange={(e)=>setReview(e.target.value)} />
              <label>Rating</label>
              <select onChange={(e)=>setRating(e.target.value)}>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                <option value="5">5</option>
              </select>
              <button type='submit'>Submit</button>
            </form>
          </div>
        </Popup>
      )}

      {currentUsername ? (
        <button className='button logout' onClick={handleLogout}>Log out</button>
      ) : (
        <div className='buttons'>
          <button 
            className='button login'
            onClick={() => setShowLogin(true)}
          >Log in</button>
          <button
            className='button'
            onClick={() => setShowRegister(true)}
          >Register</button>
        </div>
      )}
      {
        showRegister && <Register setShowRegister={setShowRegister} /> 
      }
      {
        showLogin && <Login 
          myStorage={myStorage} 
          setShowLogin={setShowLogin}
          setCurrentUsername={setCurrentUsername}
        />
      }
    </Map>
    </div>
  );
}

export default App;

I want to deploy this in Heroku. But in Heroku, I can’t run frontend and backend separately. So I am preparing the static builds and serving them from the backend server only.

Any idea why the static builds are giving the error, or the error is somewhere else.

How does React hook handle dependency lists when passing objects to child components?

Parent component like this:

function ParentComponent(){
  return (
    <ChildComponent data={{ x: 1, y: 2 }} />
  )
}

Child component like this:

function ChildComponent({ data }){
  const [sum, set] = useState(0)
  
  useEffect(() => {
    set(data.x + data.y)
  }, [data])

  return (
    <div>{sum}</div>
  )
}

If it is like the above method, it will cause repeated rendering between subgroups, because the data is always changing. How should I deal with such a scenario?

Of course I know it’s possible to cache data in the parent component by const [data] = useState({ x: 1, y: 2 }), but I want to know if there is a better solution, if any object parameter is required useState to cache, is this implementation too complicated?

In addition, it can also be stored in the child component through const dataRef = useRef(data), but if a value of data changes, it will not be recalculated.

Other parameters such as functions and arrays are the same.

What’s wrong with my thinking?

Loop through array with setInterval play button and pause it

I want to loop through a array with a pause and a start button. Right now it automatically plays and I am not sure how to connect the setInterval to the play function and not sure how to stop the interval as everything I try just crashes it. Maybe there is a good a library for doing this as I can imagine this is quite a normal thing to do? If not please help me fix my code, maybe there is better ways to do this if so please tell đŸ™‚
Codesandbox attempt: https://codesandbox.io/s/modern-dream-4kldkg?file=/src/App.js

import "./styles.css";
import { useState } from "react";
export default function App() {
  const array = [1, 2, 3, 5, 6, 7];
  const [current, setCurrent] = useState(0);
  const play = () => {
    setCurrent(current + 1);
  };
  const pause = () => {};
  const reset = () => {
    setCurrent(0);
  };
  var intervalID = setInterval(function () {
    if (current >= array.length) {
      setCurrent(0);
    }
    setCurrent(current + 1);
  }, 5000);

  return (
    <div className="App">
      <button onClick={() => play()}>play</button>
      <br></br>
      <button onClick={() => pause()} style={{ marginTop: "5px" }}>
        Pause
      </button>
      <br></br>
      <button onClick={() => reset()} style={{ marginTop: "5px" }}>
        Reset
      </button>
      <br></br>
      <h1>{array[current]}</h1>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Bootstrap popover content callback called twice on every second click

I’m trying to create a feature that will display the popover with manual click event.
My goal is to populate the popover and display newest data through ajax call after every click.

The problem I’m facing is described on the title.

For example:

1st click -> call once
2nd click -> call twice
3rd click -> call once
4th click -> call twice
... 

The code look like this:

$popoverButton.popover({
    container: 'body',
    template: `<div></div>`,
    title: 'title',
    content: function () {
        console.log('*');  // this called twice on every second click
        let id = $(this).attr('data-id');
        return initPopover(id);
    },
    html: true,
    trigger: 'manual',
});
function initPopover(id) {
    let $popover = $('<div class="popover-body"></div>');
    $popover.attr({'id': 'popover-body-' + id});
    let $spinner = $(`<div class="spinner"><span class="spinner-border"></span></div>`);
    $popover.append($spinner);
    let $sellers = $('<div class="sellers"></div>');
    $popover.append($sellers);
    return $popover;
}

To open the popover, I declared the click event with these functions:

$popoverButton.on('click', function () {
        closePopover();
        openPopover($(this));
});
closePopover() {
    $popoverButton.popover('hide');  
}
openPopover($targetButton) {
    // hide all opened popovers
    $('.popover').popover('hide');  
    $targetButton.popover('show');
    getSellersAndAppendData();
}

I’m not sure why this happened. Please help.

I’m trying to implement Infinite Scrolling in a React application using the IntersectionObserver API but i’m running into some issues

I’m trying to implement infinite scrolling and it’s supposed to work by getting data in pages from the API…and then using the IntersectionObserver API, check for intersection between the target Element and the viewport, and then when’s there one, request for the next page and get the data and add it to the previous posts…While experimenting I was able to get it to get of work but it sometimes keeps requesting for the same page and maybe goes into an infinite loop of requests. I was going to try to create a custom hook for it but because I was also using redux I did something like this:

Here’s the post component with the infinite scroll implementation:

const Posts = ({ setCurrentId }) => {

const classes = useStyles()
const dispatch = useDispatch();
const [postsArr, setPostsArr] = useState([]);
const [hasMore, setHasMore] = useState(false);

const { posts } = useSelector((state) => state.posts);
const { numberOfPages } = useSelector((state) => state.posts);
const { currentPage } = useSelector((state) => state.posts);

const [pageNum, setPageNum] = useState(1);

useEffect(() => {
    dispatch(getPosts((pageNum)))
    setPostsArr((prev) => {
        return { ...prev, posts };
    })
    setHasMore(numberOfPages > 0);
}, [pageNum, numberOfPages]);

const { loading } = useSelector((state) => state.posts);

const observer = useRef();
const lastPostElementRef = useCallback((node) => {
    if (observer.current) observer.current.disconnect();
    observer.current = new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting && hasMore) {
            setPageNum((prev) => prev + 1);
        }
        dispatch(getPosts(pageNum));
    });
    if (node) observer.current.observe(node);
    if (currentPage === numberOfPages) setHasMore(false);
}, [hasMore]);

const handleChange = (e) => {
    setPageNum(1);
};

if (!postsArr.length && !loading) return 'No posts found';
else
    return (
        <Grid className={classes.container} container alignItems="stretch" spacing={3}>
            {postsArr[0].map((post, i) => (
                (postsArr.length === i + 1) ? (
                    <Grid key={post._id} ref={lastPostElementRef} item xs={12} sm={6} md={6} lg={3} >
                        <Post post={post} setCurrentId={setCurrentId} />
                    </Grid>
                ) : (
                    <Grid key={post._id} item xs={12} sm={6} md={6} lg={3}>
                        <Post post={post} setCurrentId={setCurrentId} />
                    </Grid>
                )
            ))}
            <div>{loading && <CircularProgress />}</div>
            </Grid>
        )}
export default Posts;

Here’s the action that gets dispatched:

export const getPosts = (page) => async (dispatch) => {
try {
    dispatch({ type: START_LOADING })
    const { data: { data, currentPage, numberOfPages } } = await api.fetchPosts(Number(page));

    dispatch({ type: FETCH_ALL, payload: { data, currentPage, numberOfPages } });
    dispatch({ type: END_LOADING })
} catch (error) {
       console.log(error)
    }
}

And then the reducer:

const postReducer = (state = [], action) => {
switch (action.type) {
    case START_LOADING:
        return { ...state, loading: true };
    case END_LOADING:
        return { ...state, loading: false };
    case FETCH_ALL:
         return {
            ...state,
            posts: action.payload.data,
            currentPage: action.payload.currentPage,
            numberOfPages: action.payload.numberOfPages,
            // error: action.payload.error
        };
   default:
            return state;
    }
}
export default postReducer

Don’t think there’s a need for this but here’s the backend api controller function:

const getPosts = async (req, res) => {
const { page } = req.query;

try {
    const LIMIT = 8;
    const startIndex = (Number(page) - 1) * LIMIT; //GET THE STARTING INDEX OF EVERY PAGE
    const total = await postMessage.countDocuments({});

    const posts = await postMessage.find().sort({ _id: -1 }).limit(LIMIT).skip(startIndex);

    res.status(200).json({ data: posts, currentPage: Number(page), numberOfPages: Math.ceil(total / LIMIT) });
} catch (error) {
        res.status(404).json({ message: error.message });
    }
}

currently, posts returns this:
enter image description here

and postArr returns this:
enter image description here

Note that postArr sometimes returns undefined and the component returns this error:
enter image description here

I hope this is detailed enough and I’d really appreciate a response on what I’m doing wrong or if there’s a better way to accomplish my goal.

why does array map function return undefined [duplicate]

my code:

function splitArray() {
    var arr = [
        'aaa-bbb-ccc',
        'ddd-eee-fff',
        'ggg'
    ];

    arr = arr.map((s) => { s.split('-'); });

    console.log(arr);
}

the expected output would be:

[ 
    [ 'aaa', 'bbb', 'ccc' ], 
    [ 'ddd', 'eee', 'fff' ], 
    [ 'ggg' ] 
]

but I actually get this:

[ undefined, undefined, undefined ]

Why?

Cannot Parse properties from HTTPRequest using Javascript – Homework

I am having an issue parsing properties from the response I get to an API call. I can see the results using a console log, but when I attempt to parse the data and display it, I get “undefined” for all the properties. I know fetch is a different animal, but this is an assignment and we need to do it with GET requests. I also know modern JavaScript etiquette doesn’t require backwards compatible event listeners, but our book is from 2016.

The relevant JavaScript:

function getRequestObject() {
   try {
       httpRequest = new XMLHttpRequest();
   } catch (requestError) {
       return false;
   }
   return httpRequest;
}

function getResults(evt) {
   if (evt.preventDefault) {
       evt.preventDefault();
   } else {
       evt.returnValue = false;
   }
   var entry = document.getElementsByTagName("input")[0].value;

   if (!httpRequest) {
       httpRequest = getRequestObject();
   }
   httpRequest.abort();
   httpRequest.open("get", "https://api.bing.microsoft.com/v7.0/search?q=" + encodeURIComponent(entry) + "&count");
   httpRequest.setRequestHeader("Ocp-Apim-Subscription-Key", "fb8338ec48d44c2dbc002efd2d065b19");
   httpRequest.setRequestHeader("Content-Type", "application/json");
   httpRequest.send();
   httpRequest.onreadystatechange = displaySuggestions;
}

function displaySuggestions() {
   console.log("display request.response -" + httpRequest.response);
   if (httpRequest.readyState === 4 && httpRequest.status === 200) {
       // var response = JSON.stringify(httpRequest.response);
       var searchResults = JSON.parse(httpRequest.response);
       console.log("after - search results =" + searchResults);


       console.log(searchResults);

       var articleEl = document.getElementsByTagName("article")[0];
       console.log("name" + searchResults.name);
       for (var i = 0; i < 20; i++) {
           var newDiv = document.createElement("div");
           var head = document.createDocumentFragment();
           var newP1 = document.createElement("p");
           var newP2 = document.createElement("p");
           var newP3 = document.createElement("p");
           var newA = document.createElement("a");
           head.appendChild(newP1);
           newA.innerHTML = searchResults.Title;
           newA.setAttribute("href", searchResults.Url);
           newP1.appendChild(newA);
           newP1.className = "head";
           newP2.innerHTML = searchResults.Url;
           newP2.className = "url";
           newP3.innerHTML = searchResults.Description;
           newDiv.appendChild(head);
           newDiv.appendChild(newP2);
           newDiv.appendChild(newP3);
           articleEl.appendChild(newDiv);
       }
   }
}

It is also live on a web server, so here is the url. I am aware of the reference error, it’s just a variable that was defined using ‘getElementByID‘ and the element is not on this particular page.

Link to live version of page

Is there a cleaner way to add and delete elements on this bookshelf project using vanilla javascript? [closed]

In this project I was supposed to add and remove books by author and title by pressing the submit and remove button.
Here is a video that illustrates how my project works

https://www.loom.com/share/4ccc0b1199cb4aca8ae59ddfdfdbddfe

I did it using two functions and saving the added books into an array of objects, but i know there should be better ways to add and delete and also store those books on the local storage.

whit nothing else to say other than tanks this is the code I used:

const form = document.querySelector(".form");
const library = document.querySelector(".library");
const inputAuthor = document.querySelector(".input-author");
const inputBook = document.querySelector(".input-book");
const errormessage = document.querySelector(".errormessage");
let storedBooks = JSON.parse(localStorage.getItem("books"));
let bookShelf = [];
let filter = [];
let counter ="0"

function libraryBooks(object) {
  return  `<div class="${object.author}">
    <h1>${object.book}</h1>
    <p>${object.author}</p> 
    <hr> 
    <button class="remove">
    remove
    </button>
    </div>`
  }
  
function remove() {
  if(bookShelf.length>0){
    const removebtn = document.querySelectorAll(".remove");
    removebtn.forEach(element => element.addEventListener("click", ()=> {
      let parentNodeClass = element.parentNode.className;
      element.parentNode.remove()
      console.log(parentNodeClass)
      bookShelf = bookShelf.filter(x => x.author !== parentNodeClass)
      localStorage.setItem('books', JSON.stringify(bookShelf))
      console.log("book", bookShelf)
      console.log("store", storedBooks)
    })) 
  }
}


function add() {
  if(inputAuthor.value != "" && inputBook.value != ""){
    currentBook = []
    currentBook.push (
      {
        author: inputAuthor.value,
        book: inputBook.value
      }
    )
    filter = bookShelf.filter(x => x.book === currentBook[0].book)
    if(filter.length > 0){
      errormessage.style.display ="unset"
      inputAuthor.value = ""
      inputBook.value = ""
      setTimeout(()=>errormessage.style.display = "none",3000)
      return
    }
    bookShelf.push (
      {
        author: inputAuthor.value,
        book: inputBook.value
      }
    )   
    if(bookShelf.length>0) {
      currentBook.forEach(book => library.insertAdjacentHTML('beforeend', libraryBooks(book)))
    }
  } 
  inputAuthor.value = ""
  inputBook.value = ""
  localStorage.setItem('books', JSON.stringify(bookShelf))
}

form.addEventListener("submit", function(event) {
  event.preventDefault();
  add()
  remove()
}
)

if(storedBooks !== null){
   console.log("entré")
   bookShelf = storedBooks
   bookShelf.forEach(book => {
   library.insertAdjacentHTML('beforeend', libraryBooks(book))
   remove()
  })
}
.form  {
  display: flex;
  flex-direction: column;
  gap: 24px;
  max-width: 300px;
}

.errormessage {
  display: none;
  color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css">
    <title>Document</title>
</head>

<body>
    <h1>Aweasome Books</h1>
    <section class="library">

    </section>
    <form class = "form">
    <input class="input-author" type="text" placeholder="Author">
        <input class="input-book" type="text" placeholder="book">
    <button type="submit">
            Add
        </button>
    </form>
    <div class="errormessage">Book was added previously on your bookshelf </div>
    <script src="./app.js"></script>
</body>
</html>

Investigating chain function in js [duplicate]

This is an attempt to explore the valid answer to the following question ,

Question

We want to create a function that will add numbers together when called in succession.

add(1)(2); // == 3
We also want to be able to continue to add numbers to our chain.

add(1)(2)(3); // == 6
add(1)(2)(3)(4); //  == 10
add(1)(2)(3)(4)(5); // == 15
and so on.

A single call should be equal to the number passed in.

add(1); // == 1
We should be able to store the returned values and reuse them.

var addTwo = add(2);
addTwo; // == 2
addTwo + 5; // == 7
addTwo(3); // == 5
addTwo(3)(5); // == 10
We can assume any number being passed in will be valid whole number.

One valid answer given

function add(n) {
    var next = add.bind(n += this | 0);
    next.valueOf = function() { return n; };
    return next;
  }

When we try to console.log(add(1)(3)(4)) I am expecting the out put to be 8 (sum of 1,3 and 4) however it gives me the following out put as shown below ,

enter image description here

Thanks for any help!

Getting Missing Months

I am working on a project where I am trying to chart the number of monthly order that I have received. My current data for monthlyOrder is:

[
  {
    _id: { month: 12, year: 2021 },
    year: 2021,
    month: 'December',
    orders: 1
  },
  {
    _id: { month: 4, year: 2022 },
    year: 2022,
    month: 'April',
    orders: 31
  },
  {
    _id: { month: 5, year: 2022 },
    year: 2022,
    month: 'May',
    orders: 2
  }
]

I would like to have an array with all missing months with orders: 0, so that all months since the first month/date are included in the chart.

I have attempted to do this by:

let startYear = monthlyOrders[0]._id.year;
        let startMonth = monthlyOrders[0]._id.month;
        let endYear = monthlyOrders[monthlyOrders.length - 1]._id.year;
        let endMonth = monthlyOrders[monthlyOrders.length - 1]._id.month;
        let months = [
            'January',
            'February',
            'March',
            'April',
            'May',
            'June',
            'July',
            'August',
            'September',
            'October',
            'November',
            'December',
        ];

function getMonthlys () {
    if (startYear === endYear) {
      if (startMonth === endMonth) {
       let date = {
           month: startMonth,
           year: startYear,
       }
       if (startMonth < endMonth) {
          let months = 1;
             while (months <= endMonth) {
              months = months + 1;
              }
           let date = 
           {
               month: months,
               year: startYear,
           }
       }
    }
    }
}

However, this is probably not the best way to do this, and I am not sure how to deal with dates where startYear < endYear, but startMonth === endMonth.

Additionally, to deal with adding 0 for orders when one doesn’t exist I have tried to do this:

 let monthsObj = [];
        for (let i = startYear; i <= endYear; i++) {
            for (let j = startMonth; j <= 12; j++) {
                if (!(j > endMonth && i === endYear)) {
                    let obj = {
                        month: j,
                        year: i,
                    };
                    monthsObj.push(obj);
                }
            }
        }

        
        for (let dateVal of monthsObj) {
            let isInArray = false;

            for (let dayVal of monthlyOrders) {
                

                if (dayVal._id.year == dateVal.year && dayVal._id.month == dateVal.month) {
                    isInArray = true;
                }
            }
            if (isInArray === false) {
                let obj = {
                    month: dateVal.month,
                    year: dateVal.year,
                };
                monthlyOrders.push({ _id: obj, year: dateVal.year, month: months[dateVal.month - 1], orders: 0 });
               
            }
        }

I would really appreciate any suggestion or on how to get the:

[
  {
    _id: { month: 12, year: 2021 },
    year: 2021,
    month: 'December',
    orders: 1
  },
 {
    _id: { month: 1, year: 2022 },
    year: 2022,
    month: 'January',
    orders: 0
  },
 {
    _id: { month: 2, year: 2022 },
    year: 2022,
    month: 'February',
    orders: 0
  },
{
    _id: { month: 3, year: 2022 },
    year: 2022,
    month: 'March',
    orders: 0
  },

  {
    _id: { month: 4, year: 2022 },
    year: 2022,
    month: 'April',
    orders: 31
  },
  {
    _id: { month: 5, year: 2022 },
    year: 2022,
    month: 'May',
    orders: 2
  }
]

array that I need.

How to scroll horizontally to an item in a container while keeping it centered?

I have a list of items in a container. The container takes the full width of the parent, allowing the items to overflow horizontally if needed. Here’s what it looks like:

ul {
  list-style: none;
  display: flex;
  overflow-x: auto;
  padding: 0;
  margin: 0;
  border: 1px dotted black;
}

li {
  margin-right: 10px;
}

li:last-child {
  margin-right: 0;
}

a {
  display: block;
  text-decoration: none;
  white-space: nowrap;
  padding: 4px 8px;
  color: black;
  background-color: white;
  border: 1px solid black;
}

a.active {
  background-color: blue;
}
<ul id="container">
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#" class="active" id="element">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
  <li><a href="#">Item</a></li>
</ul>

In the list of items, there is one that has the .active class. I want to horizontally scroll the container in a way such that this item is exactly centered. To do this, I wrote the following function:

function toMiddle(element, container) {
    if (container === undefined) {
        container = window;
    }
    var elementRect = element.getBoundingClientRect();
    var absoluteElementLeft = elementRect.left;
    var middleDiff = (elementRect.width / 2);
    var scrollLeftOfElement = absoluteElementLeft + middleDiff;
    var scrollX = (scrollLeftOfElement - (container.getBoundingClientRect().width / 2));
    container.scrollTop = 0;
    container.scrollLeft = scrollX;
}

And I’m trying to call this to center the container as follows:

toMiddle(document.getElementById("element"), document.getElementById("container"));

Unfortunately, this doesn’t seem to work properly. Any idea how I can fix this? And what exactly am I doing wrong here?