Use Javascript to parse a sub-array of a JSON [duplicate]

I’m working with some JSON objects about homes. The JSON looks like the below. How would I use Javascript parsing to pull out the “yearBuilt” value? It’s part of the building array, which is part of the parcel array.

I’ve explored looping based on other similar asked-questions, but can’t arrive at anything that seems to work. Thanks!

{
   "home_value":298900,
   "page_url":"https://www.example.com/",
   "parcel":{
      "address":{
         "full":"123 Main Street",
         "city":"Raleigh",
         "state":"NC",
         "house":"2856",
         "houseExt":null,
         "street":"Jameson",
         "streetPre":"W",
         "streetPost":null,
         "streetSuffix":"Rd",
         "unit":null,
         "unitType":null,
         "zip":"27604",
         "zip4":"3776"
      },
      "apn":"1725.14-22-9727 0145193",
      "areas":[
         {
            "type":"Heated Building Area",
            "areaSquareFeet":1574
         },
         {
            "type":"Calculated Finished Area",
            "areaSquareFeet":1574
         }
      ],
      "building":[
         {
            "noOfUnits":1,
            "class":null,
            "classDescription":null,
            "quality":null,
            "condition":null,
            "architecturalStyle":"Conventional",
            "yearBuilt":1986,
            "effectiveYearBuilt":1986,
            "totalStories":2,
            "totalRooms":null,
            "bedrooms":null,
            "kitchens":null,
            "fullBaths":2,
            "baths":2,
            "comments":null,
            "occupancyStatus":"Assumed Owner Occupancy",
            "heating":"Forced air",
            "airConditioning":"Yes",
            "foundation":null,
            "fireplace":null,
            "water":null,
            "sewer":null,
            "quarterBaths":null,
            "halfBaths":0,
            "threeQuarterBaths":null
         }
      ],
      "state":"NC",
      "zoningCode":null,
      "zoningDescription":"R-6",
      "zpid":"6487528",
      "county":"Wake County"
   }
}

Is there a way to fix a batch size mismatch between output from final model layer and input?

What I’ve done: I have a complete dataset of 898 labels with a total of ~55,000 images. For purposes of speed, I took 10 of those labels and about ~600 images to test the code below. I’ve tried changing the batchSize, modifying the data function, but to no avail.

Problem: Error: Batch size mismatch: output dense_Dense1 has 10; expected 500 based on input conv2d_Conv2D1_input.

Goal: Either change the final output of dense_Dense1 to have 500, or change the expected input of conv2d_Conv2D1_input to only 10.

Complete Code:

var tf = require('@tensorflow/tfjs');
var tfnode = require('@tensorflow/tfjs-node');
var fs = require(`fs`)

const numberOfClasses = 10;

const imageWidth = 500;
const imageHeight = 800;
const imageChannels = 3;

const batchSize = 3;
const epochsValue = 5;

const createImage = async (fileName) => {
  const imageBuffer = await fs.readFileSync(fileName);
  const image = await tfnode.node.decodeImage(imageBuffer);
  return image;
}

const labelArray = indice => Array.from({length: numberOfClasses}, (_, k) => k === indice ? 1 : 0)

async function* data() {
  for (i = 1; i < numberOfClasses+1; i++) {
    for (x = 10; x < 40; x++) {
      const feature = await createImage(`./images/${i}/${i}-${x}.png`) ;
      const label = tf.tensor1d(labelArray(i))
      yield {xs: feature, ys: label};
    }
  }
}

function onBatchEnd(batch, logs) {
  console.log('Accuracy', logs.acc);
}

const main = async () => {
  const model = tf.sequential();

  model.add(tf.layers.conv2d({
    inputShape: [imageWidth, imageHeight, imageChannels],
    filters: 8,
    kernelSize: 5,
    padding: 'same',
    activation: 'relu'
  }));
  model.add(tf.layers.maxPooling2d({
    poolSize: 2,
    strides: 2
  }));

  model.add(tf.layers.conv2d({
    filters: 16,
    kernelSize: 5,
    padding: 'same',
    activation: 'relu'
  }));
  model.add(tf.layers.maxPooling2d({
    poolSize: 3,
    strides: 3
  }));
  
  model.add(tf.layers.flatten());

  model.add(tf.layers.dense({
    units: numberOfClasses,
    activation: 'softmax'
  }));

  model.compile({
    optimizer: 'sgd',
    loss: 'categoricalCrossentropy',
    metrics: ['accuracy']
  });

  model.summary()

  const ds = tf.data.generator(data);

  model.fitDataset(ds, {
    epochs: 5,
    batchSize: 10,
    callbacks: {onBatchEnd}
  }).then(info => {
    console.log('Final accuracy', info.history.acc);
  });

}
main()

Javascript eventListener inside while loop

I am trying to figure out whether it is possible in Javascript to implement an eventListener into a while loop which can pass a value to a variable inside the loop. I need this to cancel an infinite loop which continiously should send a data frame to a TCP-socket (watchdog). When the socket is closed the loop should end. I use a webworker for this purpose, but it does not work.
Here is the code:

// WebWorker with infinite loop

var check = "true";
let i=0;
let j=0;
var returnedEvent;

while(check){

self.postMessage(i);


onmessage = (event) => { 

    returnedEvent = event.data;
    console.log("worker: " + event.data);
    let check = returnedEvent;  
    }
    
    sleep(100);
    
}
console.log("loop completed");

function sleep(delay)
    {
    var start = new Date().getTime();
        while (new Date().getTime() < start + delay);
    }

in

Laravel not laoding vue js and css

i looked already in every question and couldn’t find a solution for my problem
I am looking forward to your help.
My Problem: i use Laravel 8 and tried to implement Laravel Chatter and now it’s working partly but the vue css and vue js is not loading…every normal css and js is loading Screenshot here please help me to fix this.. Heres is a screenshot from browser dev tools Screenshot from browser dev tools
Vue is already binded in app.js and everything is done
Thanks!
Greets LaviS

Link the entire box

i have the element “box” with some text and a link.

<div class="box bg-gray-300 w-48 flex-auto text-center p-10 group hover:bg-red-900 hover:cursor-pointer"><div class="group-hover:text-white">Text</div><div><a href="http://www.google.com" class="group-hover:text-white">LINK</a></div></div>

Here you can find the sample code: https://play.tailwindcss.com/uOHpX71hJq

How can i have the link AND the hover on the entire box? With Javascript i can trigger only the click, but not the hover? I found a working example on the tailwind website: enter link description here

enter image description here

How do I add extra tag at the end of every submenu in WordPress?

General Description:
I am using WordPress, I have created wordpress primary menu at the wordpress backend. In the frontend I’m displaying the dynamic menu using “wp_nav_menu” function.

Issue:
Below code is the menu in raw HTML.

<ul class="n-menu toplinks">
        <li class="home"><a href="<?php echo get_option('siteurl'); ?>">
                <p>Home</p>
            </a></li>
        <li class="s-menu"><a>
                <p>About Us</p>
            </a>
            <ul>
                <li><a href="an-overview.html"><i class="fa fa-university"></i>An Overview</a></li>
                <li><a href="#"><i class="fa fa-eye"></i>Vision & Mission</a></li>
                <li><a href="#"><i class="fa fa-history"></i>Goals</a></li>
                <li><a href="#"><i class="fa fa-pencil-square"></i>Quality Policies</a></li>
                <li><a href="#"><i class="fa fa-users"></i>Management Team</a></li>
                <li><a href="#"><i class="fa fa-check"></i>Approvals - Accreditation</a></li>
                <li><a href="#"><i class="fa fa-download" aria-hidden="true"></i>Downloads </a></li>
                <li><img src="<?php echo get_template_directory_uri(); ?>/assets/images/inner-images/nav1.jpg" alt="Image"></li>
            </ul>
        </li>
        <li class="s-menu"><a>
                <p>Admission</p>
            </a>
            <ul>
                <li><a href="#"><i class="fa fa-info"></i>Overview</a></li>
                <li><a href="#"><i class="fa fa-calendar"></i>Programme Offered</a></li>
                <li><a href="#"><i class="fa fa-address-card"></i>Admission Guidelines</a></li>
                <li><a href="#"><i class="fa fa-list"></i>Registration Guidelines</a></li>
                <li><img src="<?php echo get_template_directory_uri(); ?>/assets/images/inner-images/nav2.jpg" alt="Image"></li>
            </ul>
        </li>
        <li><a href="contact-us.html">
                <p>Contact Us</p>
            </a></li>
    </ul>

When I am using “wp_nav_menu” function to dynamically display the above menu(html raw code), then I am unable to show the end <li><img src="nav2.jpg" alt="Image"></li> tag at the end of every submenu.

Below I’m showing the “wp_nav_menu” function:

 wp_nav_menu( array(
            'theme_location'    => 'primary',
            'depth'             => 3,
            'container'         => 'div',
            'menu_class'        => 'n-menu toplinks',
            'fallback_cb'       => 'WP_Bootstrap_Navwalker::fallback',
            'walker'            => new WP_Bootstrap_Navwalker(),
        ) );

Below is my “WP_Bootstrap_Navwalker” class, that I am using:

<?php

if ( ! class_exists( 'WP_Bootstrap_Navwalker' ) ) {
    
    class WP_Bootstrap_Navwalker extends Walker_Nav_Menu {

        public function start_lvl( &$output, $depth = 0, $args = array() ) {
            $indent = str_repeat( "t", $depth );
            $output .= "n$indent<ul>n";
        }

        public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
            $indent = ( $depth ) ? str_repeat( "t", $depth ) : '';

            if ( 0 === strcasecmp( $item->attr_title, 'divider' ) && 1 === $depth ) {
                $output .= $indent . '<li role="presentation" class="divider">';
            } elseif ( 0 === strcasecmp( $item->title, 'divider' ) && 1 === $depth ) {
                $output .= $indent . '<li role="presentation" class="divider">';
            } elseif ( 0 === strcasecmp( $item->attr_title, 'dropdown-header' ) && 1 === $depth ) {
                $output .= $indent . '<li role="presentation" class="dropdown-header">' . esc_attr( $item->title );
            } elseif ( 0 === strcasecmp( $item->attr_title, 'disabled' ) ) {
                $output .= $indent . '<li role="presentation" class="disabled"><a href="#">' . esc_attr( $item->title ) . '</a>';
            } else {
                $value = '';
                $class_names = $value;
                $classes = empty( $item->classes ) ? array() : (array) $item->classes;
                $classes[] = 's-menu nav-item menu-item-' . $item->ID;
                $class_names = join( ' ', apply_filters( 's-menu home nav_menu_css_class', array_filter( $classes ), $item, $args ) );
                if ( $args->has_children ) {
                    $class_names .= ' dropdown';
                }
                if ( in_array( 'current-menu-item', $classes, true ) && 0 === $depth ) {
                    $class_names .= ' active acttl';
                }
                $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
                $id = apply_filters( 'nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args );
                $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
                $output .= $indent . '<li' . $class_names . '>';
                $atts = array();

                if ( empty( $item->attr_title ) ) {
                    $atts['title']  = ! empty( $item->title )   ? strip_tags( $item->title ) : '';
                } else {
                    $atts['title'] = $item->attr_title;
                }

                $atts['target'] = ! empty( $item->target ) ? $item->target : '';
                $atts['rel']    = ! empty( $item->xfn )    ? $item->xfn    : '';
                // If item has_children add atts to a.
                if ( $args->has_children && 0 === $depth ) {
                    $atts['href']           = '#';
                    // $atts['data-toggle']    = 'dropdown';
                    // $atts['class']          = 'dropdown-toggle';
                    // $atts['aria-haspopup']  = 'true';
                } else {
                    $atts['href'] = ! empty( $item->url ) ? $item->url : '';
                }
                $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args );
                $attributes = '';
                foreach ( $atts as $attr => $value ) {
                    if ( ! empty( $value ) ) {
                        $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
                        $attributes .= ' ' . $attr . '="' . $value . '"';
                    }
                }
                $item_output = $args->before;
                if ( ! empty( $item->attr_title ) ) {
                    $pos = strpos( esc_attr( $item->attr_title ), 'glyphicon' );
                    if ( false !== $pos ) {
                        $item_output .= '<a' . $attributes . ' class="nav-link"><span class="glyphicon ' . esc_attr( $item->attr_title ) . '" aria-hidden="true"></span>&nbsp;';
                    } else {
                        $item_output .= '<a' . $attributes . ' class="nav-link dropdown-toggle" id="navbarDropdown3"><i class="fa ' . esc_attr( $item->attr_title ) . '" aria-hidden="true"></i>&nbsp;';
                    }
                } else {
                    $item_output .= '<a' . $attributes . '><p>';
                }
                $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
                $item_output .= ( $args->has_children && 0 === $depth ) ? ' </p></a>' : '</p></a>';
                $item_output .= $args->after;
                $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
            }
        }
        public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
            if ( ! $element ) {
                return; }
            $id_field = $this->db_fields['id'];
            // Display this element.
            if ( is_object( $args[0] ) ) {
                $args[0]->has_children = ! empty( $children_elements[ $element->$id_field ] ); }
            parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
        }

        public static function fallback( $args ) {
            if ( current_user_can( 'edit_theme_options' ) ) {

                /* Get Arguments. */
                $container = $args['container'];
                $container_id = $args['container_id'];
                $container_class = $args['container_class'];
                $menu_class = $args['menu_class'];
                $menu_id = $args['menu_id'];

                if ( $container ) {
                    echo '<' . esc_attr( $container );
                    if ( $container_id ) {
                        echo ' id="' . esc_attr( $container_id ) . '"';
                    }
                    if ( $container_class ) {
                        echo ' class="' . sanitize_html_class( $container_class ) . '"'; }
                    echo '>';
                }
                echo '<ul';
                if ( $menu_id ) {
                    echo ' id="' . esc_attr( $menu_id ) . '"'; }
                if ( $menu_class ) {
                    echo ' class="' . esc_attr( $menu_class ) . '"'; }
                echo '>';
                echo '<li><a href="' . esc_url( admin_url( 'nav-menus.php' ) ) . '" title="">' . esc_attr( 'Add a menu', '' ) . '</a></li>';
                echo '</ul>';
                if ( $container ) {
                    echo '</' . esc_attr( $container ) . '>'; }
            }
        }
    }
}

Please help me to solve this issue. How do I add dynamic “li” tag at the every end of submenu !!!

Run a python script using requirements with browser JavaScript

My main goal here is to execute a python script I have written when I run a function triggered through HTML. Here is how I have things currently set up:

I have a JavaScript File containing python run functions:

const PythonShell = require('python-shell').PythonShell;
class AHK {
   static async runScript() {
     PythonShell.run('/ahk/script.py', null, function (err) {
       if (err) throw err;
       console.log('finished');
   });
}
module.exports = AHK;

I have my main.js file which would be the js code for the HTML to handle. I’d like for it to take in the module AHK. Something simple like this:

const AHK = require('./ahk');

function runFunction(x){
 if(x = 1)
    AHK.runScript()
 }

And then I have some HTML with a javascript tag

<script type="text/javascript">
let x =1; //this is just to show x is getting populated. In the actual code it's constantly changing values

async function predict() {
  if(x > 1)
    runFunction(x)
}
</script>

Biggest issue I’m facing:

I’ve become aware that browser javascript doesn’t like requirements/modules. For example, the main.js file doesn’t like having a requirement at the top. I’ve tried using things like requirejs, but I can’t seem to figure out how to make something like this work. I basically need it so that when the requirement is met and the function runFunction is run, the python script is executed on my machine.

Important to note that this is all running for a personal project on my computer, so it will never not be local.

How to get 4 random images out of array of 6 images in Javascript

I have a small problem. I need to get 4 random images out of array of 6 elements but I don’t know how to do it. Images should repeat.

let array = ["../media/pawn.png", "../media/rook.png", "../media/knight.png", "../media/bishop.png", "../media/queen.png", "../media/king.png"];
shuffleArray(array);

array.forEach(function(image) {
    let img = document.createElement('img');
    img.src = image;
    img.height = "45";
    img.width = "50";
    document.getElementById("random").appendChild(img);
});

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        let j = Math.floor(Math.random() * (i + 1));
        let temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

How to use framer motion animation with swiper.js (React)?

So the animations are only occurring during the initial page reload. I want the animations to execute every time I scroll down to another page. How do I use react-router with swiper and framer or is there any other way to do it.
This is my app.js

import React, { useRef, useState } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import Home from "./Home";
import Works from "./Works";
import "./styles.css";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import "swiper/css";
import "swiper/css/pagination";
import "swiper/css/navigation";
import Navbar from "./Navbar";

import SwiperCore, {
  Mousewheel,
  Keyboard,
  Pagination,
  Navigation,
} from "swiper";

// install Swiper modules
SwiperCore.use([Mousewheel, Pagination]);

export default function App() {
  let i = 0;
  return (
    <>
      <Swiper
        onScroll={() => {
          //console.log("Scrolled");
          localStorage.setItem("scrolled", (i = i + 1));
          console.log(localStorage.getItem("scrolled"));
        }}
        direction={"vertical"}
        slidesPerView={1}
        spaceBetween={30}
        mousewheel={true}
        className="mySwiper"
      >
        <SwiperSlide>
          <Home />
        </SwiperSlide>
        <SwiperSlide>
          <Works />
        </SwiperSlide>
        <SwiperSlide>Slide 3</SwiperSlide>
        <SwiperSlide>Slide 4</SwiperSlide>
        <SwiperSlide>Slide 5</SwiperSlide>
        <SwiperSlide>Slide 6</SwiperSlide>
        <SwiperSlide>Slide 7</SwiperSlide>
        <SwiperSlide>Slide 8</SwiperSlide>
        <SwiperSlide>Slide 9</SwiperSlide>
      </Swiper>
    </>
  );
}

This is one of my components Home.js

import React, { useEffect, useState } from "react";
import "./App.css";
import ClimbingBoxLoader from "react-spinners/ClimbingBoxLoader";
import "./mainpage.css";
import cloud1 from "./images/cloud1.svg";
import cloud02 from "./images/cloud02.svg";
import cloud2 from "./images/cloud2.svg";
import moon from "./images/moon.svg";
import cloud3 from "./images/cloud3.svg";
import cloud01 from "./images/cloud01.svg";
import { useNavigate } from "react-router-dom";
import {
  MouseParallaxChild,
  MouseParallaxContainer,
} from "react-parallax-mouse";
import Navbar from "./Navbar";
import { motion, useViewportScroll, useTransform } from "framer-motion";

function Home() {
  const fadeLeft = {
    hidden: { opacity: 0, x: -100 },
    visible: { opacity: 1, x: 0 },
  };

  const fadeRight = {
    hidden: { opacity: 0, x: 100 },
    visible: { opacity: 1, x: 0 },
  };

  const [loading, setloading] = useState(false);
  useEffect(() => {
    setloading(true);
    setTimeout(() => {
      setloading(false);
    }, 1000);
  }, []);

  return (
    <MouseParallaxContainer className="App">
      {loading ? (
        <ClimbingBoxLoader size={20} color={"#F37A24"} loading={loading} />
      ) : (
        <MouseParallaxContainer
          className="main-page"
          containerStyles={{
            width: "100%",
            overflow: "none",
          }}
        >
          <Navbar />
          <motion.h1
            variants={fadeLeft}
            initial="hidden"
            animate="visible"
            transition={{ duration: 0.5 }}
            className="heading"
          >
            SASWATA
          </motion.h1>
          <motion.h1
            variants={fadeLeft}
            initial="hidden"
            animate="visible"
            transition={{ duration: 0.5 }}
            className="heading2"
          >
            GHOSH
          </motion.h1>
          <motion.span
            variants={fadeLeft}
            initial="hidden"
            animate="visible"
            transition={{ duration: 0.7 }}
            className="bar1"
          ></motion.span>
          <motion.span
            variants={fadeLeft}
            initial="hidden"
            animate="visible"
            transition={{ duration: 0.85 }}
            className="bar2"
          ></motion.span>
          <motion.p
            variants={fadeLeft}
            initial="hidden"
            animate="visible"
            transition={{ duration: 1 }}
            className="para"
          >
            web developer
          </motion.p>
          <p className="scrolldown">SCROLL DOWN</p>
          <span className="verticaline"></span>
          <MouseParallaxContainer
            className="moon"
            containerStyles={{
              width: "100%",
              overflow: "none",
            }}
          >
            <MouseParallaxChild
              className="moon_text"
              factorX={0.01}
              factorY={0.01}
            >
              <motion.p
                variants={fadeRight}
                initial="hidden"
                animate="visible"
                transition={{ duration: 0.5 }}
              >
                PORTFOLIO
              </motion.p>
            </MouseParallaxChild>
            <MouseParallaxChild
              className="moon_img"
              factorX={0.03}
              factorY={0.05}
            >
              <motion.img
                variants={fadeRight}
                initial="hidden"
                animate="visible"
                transition={{ duration: 0.7 }}
                src={moon}
                alt=""
              />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud01"
              factorX={0.04}
              factorY={0.06}
            >
              <motion.img
                variants={fadeRight}
                initial="hidden"
                animate="visible"
                transition={{ duration: 0.8 }}
                src={cloud01}
                alt=""
              />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud02"
              factorX={0.03}
              factorY={0.05}
            >
              <motion.img
                variants={fadeRight}
                initial="hidden"
                animate="visible"
                transition={{ duration: 0.5 }}
                src={cloud02}
                alt=""
              />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud_front1"
              factorX={0.04}
              factorY={0.07}
            >
              <motion.img
                variants={fadeRight}
                initial="hidden"
                animate="visible"
                transition={{ duration: 0.7 }}
                src={cloud1}
                alt="cloud1"
              />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud3"
              factorX={0.03}
              factorY={0.05}
            >
              <motion.img
                variants={fadeRight}
                initial="hidden"
                animate="visible"
                transition={{ duration: 0.5 }}
                src={cloud3}
                alt=""
              />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud2"
              factorX={0.06}
              factorY={0.05}
            >
              <motion.img
                variants={fadeRight}
                initial="hidden"
                animate="visible"
                transition={{ duration: 0.5 }}
                src={cloud2}
                alt="cloud2"
              />
            </MouseParallaxChild>
          </MouseParallaxContainer>
          <div className="nav-left">
            <span style={{ width: "40px" }} className="span1"></span>
            <span style={{ width: "25px" }} className="span2"></span>
            <span style={{ width: "25px" }} className="span3"></span>
            <span style={{ width: "25px" }} className="span4"></span>
          </div>
        </MouseParallaxContainer>
      )}
    </MouseParallaxContainer>
  );
}

export default Home;

After going through several videos and documentation I was not able to figure it out.

Split an array into an array with different objects

I was working on a plain array but I want the structure of the array to be in a sub-array form with multiple entries inside it. I tried forEach but when I push the element the whole array is pushed inside the sub-array.
The array that I have

data = ["1640662522","1640663240","1640663967","1640664659","1640665388","1640666124","1640666829","1640667505","1640668278","1640668984"];

but I want the structure of my new array to be

    {
"sizeData":[
 {
           "timestamp":1640662522,
           "size":12345,
           "fees":12589,
           "cost":168
},
 {
           "timestamp":1640663240,
           "size":12345,
           "fees":12589,
           "cost":168},
 {
           "timestamp":1640663967,
           "size":12345,
           "fees":12589,
           "cost":168
}, {
           "timestamp":1640664659,
           "size":12345,
           "fees":12589,
           "cost":168
}
]

Could anyone help me on this.
I am working on js for this

sort in descending if obj of array is number.else in ascending order. in angular javascript

i have an array of objects. if each obj consists of year followed by title. then year should be in descending order and title should be in ascending order.

ex:
i have an array like
[2018 Apple,2017 Car , 2022 Ball ,2021 Dog,2021 Box,2018 Bat];

my sorting requirement would be like

[2022 Ball, 2021 Box , 2021 Dog , 2018 Apple ,2018 Bat,2017Car]

if you observe for 2021 and 2018 their titles are appearing in ascending and all years are appearing in descending.

in javascript /angular!