Sort array based on string transformed into date

So I have an array containing reviews (which I retrieve from firebase firestore). The field ‘date’ is string in firestore. How can I sort the reviews in descending order based on this date? I have tried this but they are in the retrieval order.

const getReviews=async()=>{
        let reviewsClone=[];
        const q = query(collection(db, "reviews"), where("product", "==", uniqueProductName.product));
        const querySnapshot=await getDocs(q);
        querySnapshot.forEach((doc)=>{
            reviewsClone.push(doc.id);
        })

        reviewsClone.sort(function(a,b){
            return new Date(a.date) - new Date(b.date);
          });
        setReviews(reviewsClone);

    }

Thank you in advance.

Node JS – How do I close an SSH connection after querying a database using the SSH2 module

I’m fairly new to JS.
Below is what I have so far.
After getting the required results from the query, the connection remains on.
I have tried using .end() and .close() methods, but the connection still remains open.
I would like to end all connections after attaining results from a query, any suggestions?

Many thanks

const mysql = require('mysql2');
const { Client } = require('ssh2');
const sshClient = new Client();
const fs = require('fs');
require("dotenv").config();

const dbServer = {
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    user: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_DATABASE
}
const tunnelConfig = {
    host: process.env.DB_SSH_HOST,
    port: 22,
    username: process.env.DB_SSH_USER,
    password: process.env.DB_SSH_PASSWORD,
    privateKey: fs.readFileSync(process.env.HOME + '/.ssh/id_rsa')
}
const forwardConfig = {
    srcHost: '127.0.0.1',
    srcPort: 3306,
    dstHost: dbServer.host,
    dstPort: dbServer.port
};
const SSHConnection = new Promise((resolve, reject) => {
    sshClient.on('ready', () => {
        sshClient.forwardOut(
        forwardConfig.srcHost,
        forwardConfig.srcPort,
        forwardConfig.dstHost,
        forwardConfig.dstPort,
        (err, stream) => {
             if (err) reject(err);
             const updatedDbServer = {
                 ...dbServer,
                 stream
            };
            const connection =  mysql.createConnection(updatedDbServer);
           connection.connect((error) => {
            if (error) {
                reject(error);
            }
            resolve(connection)
            

            });
        });
    }).connect(tunnelConfig);
});

SSHConnection.then(client => {
    client.query('SELECT * FROM pimcore.object_query_19', function (err, results, fields) {
        if (err) throw err;
        else {
        console.log(results)
        client.close()}
    })
});


Can I target dropzone to a div instead of a form? If not can I easily overide the white background and border?

I followed this lesson from the docs and ran into an issue with the dropzone class. It styles the background white and makes the entire form area clickable/droppable. I tried to fix this with the clickable setting but I can not seem to be able to get it to work correctly. When I try to put the dropzone class inside thedropzone-previews div it does not target the dropzone logic to the div properly. Is there a way to get dropzone to target a specific element?

Current form with wtf validation.

                    <form id="product-upload" class="dropzone" action="{{ url_for('main.upload_products') }}">
                        <div class="col-sm-12 mb-3">
                            {{ productForm.title.label }}
                            {{ productForm.title(class="form-control") }}
                            <div id="title-error" class="invalid-feedback"></div>

                            {{ productForm.description.label }}
                            {{ productForm.description(class="form-control") }}
                            <div id="description-error" class="invalid-feedback"></div>

                            {{ productForm.cost.label }}
                            {{ productForm.cost(class="form-control") }}
                            <div id="cost-error" class="invalid-feedback"></div>

                            {{ productForm.old_cost.label }}
                            {{ productForm.old_cost(class="form-control") }}
                            <div id="old_cost-error" class="invalid-feedback"></div>
                        </div>
                        <div class="dropzone-previews mb-4"></div>
                        {{ productForm.productsubmit(id='product-btn', class="btn btn-secondary") }}
                    </form>

Here is the script that activates my dropzone logic.

                    <script>
                            //Dropzone.autoDiscover = false;  
                            Dropzone.options.productUpload = { // camelized version of the `id`
                                maxFilesize: {{ config.MAX_CONTENT_LENGTH }}/(1024*1024), // MB
                                autoProcessQueue: false,
                                uploadMultiple: true,
                                parallelUploads: 100,
                                maxFiles: 100,
                                //clickable: '#dropzone-previews',
                                previewsContainer: '.dropzone-previews',
                                addRemoveLinks: true,
                                //forceFallback: true,//disable validators to test server validators
                                //url: "{{ url_for('main.upload_products') }}"
                            };
                    <script>

Cannot Post/ in express js

I have the following code and also have defined the response for POST/messages but when I go to /bc/add and submit a form it shows that Cannot POST /messages.
Can you please explain me the reason?
Here is my code :

 const express = require("express");
  const bodyParser = require("body-parser");

  const app = express();
  app.use(bodyParser.urlencoded({ extended: false }));
 

  app.use("/bc/add", (req, res, next) => {
    console.log("In the next middleware !", req.url);
    res.send(
      '<form action="/messages" method="post"><input  type="text" name="message"><button type="submit">Submit </button></form>'
    );

    app.use("/s", (req, res, next) => {
      res.send("hup");
    });

    app.post("/messages", (req, res, next) => {
      console.log(req.body);
      console.log("In the middleware !", req.url);
      res.redirect("/s");
    });
  });


  app.use("/favicon.ico", (req, res, next) => {
    console.log("In the middleware !", req.url);
    res.sendStatus(204);
  });
  app.listen(3000, () => {
    console.log("Server running at port 3000");
  });

Generate new order of numbers from array

I’m currently trying to generate a new order of numbers from a current array with numbers from 1 – 10.

For example, I have arrary like this:

data = [
    {
        0: 1,
        1: 2,
        2: 3,
        3: 4,
        4: 5,
        5: 6
    },
    {
        0: 1,
        1: 2,
        2: 3,
        3: 4,
        4: 5,
        5: 8
    }
]

And i’m trying to generate a new order from this array from numbers from 1 – 10.

For example:
I want it to generate a new order like this:

    0: 1,
    1: 2,
    2: 3,
    3: 4,
    4: 5,
    5: 7 (The new number)

Where it checks the order of the array, and make a new order with numbers from 1 – 10

affiliateCommissionPrice = (affiliateCommissionPrice * $ CommissionPrice) / $ CommissionØ›

I hope you are well ,I have a problem with the result of this code

$affiliateCommissionPrice =  ($affiliateCommissionPrice * $commissionPrice) / 
$commission; 

$commissionPrice = $commissionPrice - $affiliateCommissionPrice;

We use this code for the purpose of the referral for the training platform.

  • affiliateCommissionPrice= affiliateCommission rate
  • commissionPrice=platform profit rate
  • commission=Coach’s Revenue Ratio

Now this code is calculated according to the following approach:

  • For example, a course costs $100.
  • If the platform percentage is 30% and the referral percentage is 5%
  • The deduction is done according to the following: 25% of the platform rate, 5% of the referral rate, and 70% of the coach

Quite simply, it is deducted from the referral percentage from the platform, not the coach. Is there any help to improve my code so that the percentage of the platform remains fixed and the deduction is only from the coach?

Push data from console.log to html

const access_token = ""


fetch('https://api.fitbit.com/1/user/-/profile.json', {
    method: "GET",
    headers: {"Authorization": "Bearer " + access_token}
})
.then(response => response.json())
//.then(json => console.log(json))
.then((out) =>
{ 
   
    console.log(out.data);
    document.getElementById('log').innerHTML=out.data;
    
})

hi, I have been trying to fetch wep API using the above js code. i have successfully fetched the data inside my debug console but after modify it to fetch inside HTML, shows undefined. Can someone help me. For security purpose i removed the access token.

Form post data is not passing back to html file in django

I am creating a Django app and I am trying to show the data received from a POST request on an HTML table. I have used JavaScript fetch API to submit the form and fetch the data in views.py . I am able to fetch the form data in views.py but I am not able to send it back to the HTML file to show the same data on a table.

Without the fetch API submit, everything is working fine as per my need.

I can’t get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where I am going wrong.

views.py

def home(request):

    if request.method=="POST":

        options_value=request.POST['dropdown_val']

        value=request.POST['val']

        print(options_value,value)

  return render(request, 'index.html',context)

index.html

<form method="POST" action="" id="form">

      {% csrf_token %}

      <div class="d-flex justify-content-center" style="margin-top: 6rem">

        <div class="dropdown" style="display: flex" id="dropdown">

          <select

            class="form-select"

            aria-label="Default select example"

            name="options_value"

            id="dropdown_val"

          >

            <option disabled hidden selected>---Select---</option>

            <option value="1">Profile UID</option>

            <option value="2">Employee ID</option>

            <option value="3">Email ID</option>

            <option value="4">LAN ID</option>

          </select>

        </div>

<div class="col-3 bg-light" style="margin-left: 2rem">

          <input

            type="text"

            class="form-control"

            type="text"

            placeholder="Enter Value"

            name="value"

            id="value"

          />

        </div>
 <div style="margin-left: 2rem">

          <input

            class="btn btn-primary"

            type="submit"

            value="Submit"

            style="background-color: #3a0ca3"

          />

        </div>

      </div>

    </form>

<table style="display: table" id="table">

        <tbody>

            <tr>

              <th scope="row">ProfileUID :</th>

              <td>{{options_value}}</td>

            </tr>
            
            <tr>

              <th scope="row">First Nane :</th>

              <td>{{value}}</td>

            </tr>

        </tbody>

      </table>

<script>

      let form = document.getElementById("form");

      let dropdown_val = document.getElementById("dropdown_val");

      let val = document.getElementById("value");

      const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value;



      form.addEventListener("submit", (e) => {

        e.preventDefault();

        const newform = new FormData();

        newform.append("dropdown_val", dropdown_val.value);

        newform.append("val", val.value);

        newform.append("csrfmiddlewaretoken", csrf);

        fetch("", {

          method: "POST",

          body: newform,

        })


      .then(response => response.json())
      .then(data => {
       console.log('Success:', data);
       })
       .catch(error => {
       console.error('Error:', error);
       });

      });

    </script>

How to fix JS Files not working in Understrap Child theme

kindly assist
I am using the Understrap Child theme to build my site. All my CSS files are working properly but my JS files are not working.
I have the following code in my Html

<script src="/js/jquery.min.js"></script>
<script src="js/wow.min.js"></script>
<script src="js/smoothscroll.js"></script>
<script src="js/animsition.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/jquery.magnific-popup.min.js"></script>
<script src="js/owl.carousel.min.js"></script>
<script src="js/jquery.pagepiling.min.js"></script> 

My enqueue.php file has the following code

<?php
/**
 * Understrap enqueue scripts
 *
 * @package Understrap
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

if ( ! function_exists( 'understrap_scripts' ) ) {
    /**
     * Load theme's JavaScript and CSS sources.
     */
    function understrap_scripts() {
        // Get the theme data.
        $the_theme         = wp_get_theme();
        $theme_version     = $the_theme->get( 'Version' );
        $bootstrap_version = get_theme_mod( 'understrap_bootstrap_version', 'bootstrap4' );
        $suffix            = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';

        // Grab asset urls.
        $theme_styles  = "/css/theme{$suffix}.css";
        $theme_scripts = "/js/theme{$suffix}.js";
        if ( 'bootstrap4' === $bootstrap_version ) {
            $theme_styles  = "/css/theme-bootstrap4{$suffix}.css";
            $theme_scripts = "/js/theme-bootstrap4{$suffix}.js";
        }

        $css_version = $theme_version . '.' . filemtime( get_template_directory() . $theme_styles );
        wp_enqueue_style( 'understrap-styles', get_template_directory_uri() . $theme_styles, array(), $css_version );

        wp_enqueue_script( 'jquery' );

        $js_version = $theme_version . '.' . filemtime( get_template_directory() . $theme_scripts );
        wp_enqueue_script( 'understrap-scripts', get_template_directory_uri() . $theme_scripts, array(), $js_version, true );

        wp_enqueue_script( 'carousel-scripts', get_template_directory_uri() . '/js/owl.carousel.min.js', array(), $theme_version, true ); 
        wp_enqueue_script( 'popup-scripts', get_template_directory_uri() . '/js/jquery.magnific-popup.min.js', array(), $theme_version, true ); 
        wp_enqueue_script( 'wow-scripts', get_template_directory_uri() . '/js/wow.min.js', array(), $theme_version, true ); 
        wp_enqueue_script( 'pagepiling-scripts', get_template_directory_uri() . '/js/jquery.pagepiling.min.js', array(), $theme_version, true ); 
        wp_enqueue_script( 'smoothscroll-scripts', get_template_directory_uri() . '/js/smoothscroll.js', array(), $theme_version, true ); 
        wp_enqueue_script( 'validate-scripts', get_template_directory_uri() . '/js/jquery.validate.min.js', array(), $theme_version, true ); 
        wp_enqueue_script( 'jquery-scripts', get_template_directory_uri() . '/js/jquery.min.js', array(), $theme_version, true ); 


        if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
            wp_enqueue_script( 'comment-reply' );
        }
    }
} // End of if function_exists( 'understrap_scripts' ).

add_action( 'wp_enqueue_scripts', 'understrap_scripts' );

I have copied the inc folder from parent theme to the child theme and modified my functions.php file as follows

<?php
/**
 * Understrap Child Theme functions and definitions
 *
 * @package UnderstrapChild
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;


// UnderStrap's includes directory.
$understrap_inc_dir = get_stylesheet_directory() . '/inc';

// Array of files to include.
$understrap_includes = array(
    '/theme-settings.php',                  // Initialize theme default settings.
    '/setup.php',                           // Theme setup and custom theme supports.
    '/widgets.php',                         // Register widget area.
    '/enqueue.php',                         // Enqueue scripts and styles.
    '/template-tags.php',                   // Custom template tags for this theme.
    '/pagination.php',                      // Custom pagination for this theme.
    '/hooks.php',                           // Custom hooks.
    '/extras.php',                          // Custom functions that act independently of the theme templates.
    '/customizer.php',                      // Customizer additions.
    '/custom-comments.php',                 // Custom Comments file.
    '/class-wp-bootstrap-navwalker.php',    // Load custom WordPress nav walker. Trying to get deeper navigation? Check out: https://github.com/understrap/understrap/issues/567.
    '/editor.php',                          // Load Editor functions.
    '/deprecated.php',                      // Load deprecated functions.
);

// Load WooCommerce functions if WooCommerce is activated.
if ( class_exists( 'WooCommerce' ) ) {
    $understrap_includes[] = '/woocommerce.php';
}

// Load Jetpack compatibility file if Jetpack is activiated.
if ( class_exists( 'Jetpack' ) ) {
    $understrap_includes[] = '/jetpack.php';
}

// Include files.
foreach ( $understrap_includes as $file ) {
    require_once $understrap_inc_dir . $file;
}

/**
 * Removes the parent themes stylesheet and scripts from inc/enqueue.php
 */
function understrap_remove_scripts() {
    wp_dequeue_style( 'understrap-styles' );
    wp_deregister_style( 'understrap-styles' );

    wp_dequeue_script( 'understrap-scripts' );
    wp_deregister_script( 'understrap-scripts' );
}
add_action( 'wp_enqueue_scripts', 'understrap_remove_scripts', 20 );



/**
 * Enqueue our stylesheet and javascript file
 */
function theme_enqueue_styles() {

    // Get the theme data.
    $the_theme = wp_get_theme();

    $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
    // Grab asset urls.
    $theme_styles  = "/css/child-theme{$suffix}.css";
    $theme_scripts = "/js/child-theme{$suffix}.js";

    wp_enqueue_style( 'child-understrap-styles', get_stylesheet_directory_uri() . $theme_styles, array(), $the_theme->get( 'Version' ) );
    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'child-understrap-scripts', get_stylesheet_directory_uri() . $theme_scripts, array(), $the_theme->get( 'Version' ), true );
    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
        wp_enqueue_script( 'comment-reply' );
    }
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );



/**
 * Load the child theme's text domain
 */
function add_child_theme_textdomain() {
    load_child_theme_textdomain( 'understrap-child', get_stylesheet_directory() . '/languages' );
}
add_action( 'after_setup_theme', 'add_child_theme_textdomain' );



/**
 * Overrides the theme_mod to default to Bootstrap 5
 *
 * This function uses the `theme_mod_{$name}` hook and
 * can be duplicated to override other theme settings.
 *
 * @param string $current_mod The current value of the theme_mod.
 * @return string
 */
function understrap_default_bootstrap_version( $current_mod ) {
    return 'bootstrap5';
}
add_filter( 'theme_mod_understrap_bootstrap_version', 'understrap_default_bootstrap_version', 20 );



/**
 * Loads javascript for showing customizer warning dialog.
 */
function understrap_child_customize_controls_js() {
    wp_enqueue_script(
        'understrap_child_customizer',
        get_stylesheet_directory_uri() . '/js/customizer-controls.js',
        array( 'customize-preview' ),
        '20130508',
        true
    );
}
add_action( 'customize_controls_enqueue_scripts', 'understrap_child_customize_controls_js' );

What I have in my Chrome developer tools is this
Developer tools view

I have my js files in the js folder of Understrap child theme and not the one under src folder.
Kindly help me fix this issue I’ll be grateful.

Storing javascript date object in mongodb is different for localhost and cloud hosting

When I tested the code new Date(new Date().setHours(0, 0, 0, 0)) locally, the value is storing like this 2022-06-20T18:30:00.000+00:00, and when I hosted the same in vercel and tried the same and it is storing the date as 2022-05-21T00:00:00.000+00:00.

My requirement is, I want to save the date only in mongodb through node js, for querying and fetching the data based on the date.

How can I store the same date from both localhost and server.

javascript – remove a specific key from all instances in an object

I have nested JS objects, which I am getting from a webmethod (C#) like:

{
  "__type": "App.ApplePay.PaymentRequest",
  "countryCode": "US",
  "currencyCode": "USD",
  "lineItems": [
    {
      "label": "Product Title here",
      "amount": "3600.00",
      "type": "final"
    },
    {
      "label": "Subtotal",
      "amount": "3600.00",
      "type": "final"
    },
    {
      "label": "Complimentary Express Delivery",
      "amount": "0.00",
      "type": "final"
    },
    {
      "label": "Estimated Tax",
      "amount": "0.00",
      "type": "final"
    }
  ],
  "total": {
    "label": "Shop Name",
    "amount": "3600.00"
  },
  "supportedNetworks": [
    "masterCard",
    "visa",
    "discover"
  ],
  "merchantCapabilities": [
    "supports3DS"
  ],
  "shippingMethods": [
    {
      "label": "Complimentary Express Delivery",
      "amount": "0.00",
      "identifier": "exp-delivery-free",
      "detail": "complimentary express delivery"
    }
  ],
  "shippingContact": {
    "__type": "App.ApplePay.ContactInfo",
    "phoneNumber": null,
    "emailAddress": null,
    "givenName": null,
    "familyName": null,
    "phoneticGivenName": null,
    "phoneticFamilyName": null,
    "addressLines": null,
    "subLocality": null,
    "locality": null,
    "postalCode": null,
    "subAdministrativeArea": null,
    "administrativeArea": null,
    "country": null,
    "countryCode": null
  },
  "requiredBillingContactFields": [
    "email",
    "phone",
    "postalAddress"
  ],
  "requiredShippingContactFields": [
    "email",
    "phone",
    "postalAddress"
  ],
  "shippingContactEditingMode": null
}

Desire output:

  1. I want to remove the __type property from any level deep from all the objects. Objects can be nested within objects, and arrays as well.
  2. I want to remove property which value either Null or Empty from any level deep from all the objects.
  3. If the property is object (e.g. shippingContact) and all the value inside it are null then delete the main key, i.e shippingContact.
  const apiObject = {
    "__type": "App.ApplePay.PaymentRequest",
    "countryCode": "US",
    "currencyCode": "USD",
    "lineItems": [
      {
        "label": "Product Title here",
        "amount": "3600.00",
        "type": "final"
      },
      {
        "label": "Subtotal",
        "amount": "3600.00",
        "type": "final"
      },
      {
        "label": "Complimentary Express Delivery",
        "amount": "0.00",
        "type": "final"
      },
      {
        "label": "Estimated Tax",
        "amount": "0.00",
        "type": "final"
      }
    ],
    "total": {
      "label": "Shop Name",
      "amount": "3600.00"
    },
    "supportedNetworks": [
      "masterCard",
      "visa",
      "discover"
    ],
    "merchantCapabilities": [
      "supports3DS"
    ],
    "shippingMethods": [
      {
        "label": "Complimentary Express Delivery",
        "amount": "0.00",
        "identifier": "exp-delivery-free",
        "detail": "complimentary express delivery"
      }
    ],
    "shippingContact": {
      "__type": "App.ApplePay.ContactInfo",
      "phoneNumber": null,
      "emailAddress": null,
      "givenName": null,
      "familyName": null,
      "phoneticGivenName": null,
      "phoneticFamilyName": null,
      "addressLines": null,
      "subLocality": null,
      "locality": null,
      "postalCode": null,
      "subAdministrativeArea": null,
      "administrativeArea": null,
      "country": null,
      "countryCode": null
    },
    "requiredBillingContactFields": [
      "email",
      "phone",
      "postalAddress"
    ],
    "requiredShippingContactFields": [
      "email",
      "phone",
      "postalAddress"
    ],
    "shippingContactEditingMode": null
  };

  function sanitizeObject(obj) {
    for (var propName in obj) {
        if (!obj.hasOwnProperty(propName)) continue;
        if(!Array.isArray(obj[propName]) && typeof obj[propName] == "object"){
            sanitizeObject(obj[propName]);
        } else if(propName == "__type" || obj[propName] == null || obj[propName] == "undefined" || obj[propName] == ""){
            delete obj[propName];
        }
    }
    return obj;
  }
  
  console.log(sanitizeObject(apiObject));

But seems to be not working as expected. Any help?

Javascript – Storing an array table ascending/descending

I am trying to have a sort function on each column in my table.
I have got the name sort function working. But only the ascending function working on the ‘title’ column. I followed a guide on how to make this, and I am now wanting each column its own unique sort. But I can’t seem to figure it out.

Any help?

Thanks everyone.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<style>
    th{ 
        cursor: pointer;
        color:#fff;
            }
</style>


<table class="table table-striped">
    <tr  class="bg-info">
        <th  class="bg-info" data-colname="name" data-order="descname">Name &#9650</th>
        <th  data-coltitle="title" data-order="desctitle">Title &#9650</th>
        <th  data-colgenre="genre">Genre &#9650</th>
        <th  data-colrating="rating">Rating 0-5 &#9650</th>
        <th  data-colcountry="country">Country &#9650</th>
    </tr>
    <tbody id="myTable">
        
    </tbody>
</table>


<script>
var myArray = [
    {'name':'Alexievich, S', 'title':'The Unwomanly Face of War', 'genre': 'Biography', 'rating':'5', "country": "Belarus"},
    {'name':'Alexievich, S', 'title':'Chernobyl Prayer', 'genre': 'Biography', 'rating':'5', "country": "Belarus"},
    {'name':'Barrister, S', 'title':"The Secret Barrister: Stories of the Law and How It's Broken", 'genre': 'Autobiography', 'rating':'5', "country": "United Kingdom"},
    {'name':'Barrister, S', 'title':"Fake Law: The Truth About Justice in an Age of Lies", 'genre': 'Autobiography', 'rating':'4', "country": "United Kingdom"},
    {'name':'Bradbury, R', 'title': 'Farenheit 451', 'genre': 'Dystopian', 'rating':'4', "country": "United States"},
    {'name':'Defoe, D', 'title':"Robinson Cruseo", 'genre': 'Adventure Fiction', 'rating':'3', "country": "United Kingdom"},
    {'name':'Dick, P', 'title':"The Man in The High Castle", 'genre': 'Alternate History', 'rating':'3', "country": "United States"},
    {'name':'Dickens, C', 'title':"A Tale of Two Cities", 'genre': 'Historical Fiction', 'rating':'4', "country": "United Kingdom"},
    {'name':'Doyle, A.C', 'title':"The Hound of Baskervilles", 'genre': 'Mystery', 'rating':'4', "country": "United Kingdom"},
    {'name':'Dronfield, J', 'title':"The Boy Who Followed His Father Into Auschwitz", 'genre': 'Biography', 'rating':'5', "country": "United Kingdom"},
    {'name':'Fitzgerald, F.S', 'title':"The Great Gatsby", 'genre': 'Historical Fiction', 'rating':'4', "country": "United States"},
    {'name':'Gombrich, E', 'title':"A Little History Of The World", 'genre': 'History', 'rating':'5', "country": "Austria"},

]


buildTable(myArray)



$('th').on('click', function(){
     var column = $(this).data('colname')
     var columntitle = $(this).data('coltitle')
     var order = $(this).data('order')
     var ordertitle = $(this).data('ordertitle')
     var text = $(this).html()
     text = text.substring(0, text.length - 1);
     
     
     
    if (order == 'descname'){
        myArray = myArray.sort((a, b) => a[column] > b[column] ? 1 : -1)
        $(this).data("order","ascname");
        text += '&#9660'}

    else if(order == 'desctitle'){
        myArray = myArray.sort((a, b) => a[columntitle] > b[columntitle] ? 1 : -1)
        $(this).data("ordertitle","asctitle");
        text += '&#9660'}

    else if(order == 'desctitle'){
        myArray = myArray.sort((a, b) => a[columntitle] < b[columntitle] ? 1 : -1)
        $(this).data("ordertitle","desctitle");
        text += '&#9660'          

    
    }else{
        myArray = myArray.sort((a, b) => a[column] < b[column] ? 1 : -1)
        $(this).data("order","descname");
        text += '&#9650'
    }

    $(this).html(text)
    buildTable(myArray)
    })


   
 
    
function buildTable(data){
    var table = document.getElementById('myTable')
    table.innerHTML = ''
    for (var i = 0; i < data.length; i++){
        var colname = `name-${i}`
        var coltitle = `title-${i}`
        var colgenre = `genre-${i}`
        var colrating = `rating-${i}`
        var colcountry = `country-${i}`

        var row = `<tr>
                        <td>${data[i].name}</td>
                        <td>${data[i].title}</td>
                        <td>${data[i].genre}</td>
                        <td>${data[i].rating}</td>
                        <td>${data[i].country}</td>
                   </tr>`
        table.innerHTML += row
    }
}

</script>

How to update my Message Select menu in discord.js if i am creating a class called Pagination

Basically I’m making a discord pagination , where I create a class called Pageination . But I can’t get any idea to update my message selection menu automatically because I am using this.rows to set the rows. i dont know how to update my select menu please help me
Here are my codes:
(I’ve only included the code that’s important to show)

export class Pagination {
....
  constructor(args?: DPagination) {
    this.rows = [];
    this.setUp(args);
    this.page = 0;
  }
  private setUp(args: DPagination | undefined) {
    if (typeof args !== "object") return;
    this.ZER_WIDTH_SPACE = "u200B";
    this.pages = args.pages ? this.checkPages(args.pages) : [];
    this.showbuttons =
      "buttons" in args ? this.checkBtn(args.buttons) : defaulttest;
    this.timeout = "timeout" in args ? this.checkTime(args.timeout) : 120_000;
    this.initialText = args?.initialText ?? null;
    this.loadingMsg = args?.loadingMsg ?? null;
    this.PageSelection =
      "PageSelection" in args ? this.checkSelection(args.PageSelection) : null;
    this.attachments =
      "attachments" in args ? this.checkAttactment(args.attachments) : [];
  }
//.......
  set EmojiReaction(val: boolean) {
    if (typeof val !== "boolean")
      throw new DJ_P_Error(
        `EmojiReaction value must be of boolean type . got ${typeof val}`
      );
    this.reaction = val;
  }
// some check codes 
//......
//.....
  private getButtons(btn: TestButtons): {
    button: MessageButton[];
    emoji: EmojiBtn;
  } {
    const button: MessageButton[] = [];
    const emoji: EmojiBtn = {};
    for (const [key, value] of Object.entries(btn)) {
      if (value.visible) {
        if (this.reaction) {
          emoji[key as keyof EmojiBtn] = value.emoji;
        } else {
          button.push(
            new MessageButton({
              style: value.style ?? "PRIMARY",
              emoji: value.emoji,
              customId: key,
            })
          );
        }
      }
    }
    return {
      button,
      emoji,
    };
  }
  private getRows() {
    const rowArr = [];
    if (this.buttons.length > 5) {
      rowArr.push(
        new MessageActionRow().addComponents(...this.buttons.slice(0, 5)),
        new MessageActionRow().addComponents(
          ...this.buttons.slice(5, this.buttons.length)
        )
      );
    } else {
      rowArr.push(new MessageActionRow().addComponents(...this.buttons));
    }
    return rowArr;
  }
  private checkSelection(
    options: string[] | null | boolean | undefined
  ): MessageSelectOptionData[][] | null {
    const option: MessageSelectOptionData[] = [];
    if (typeof options === "boolean" && options) {
      const test = this.pages.map((e, i) => {
        option.push({
          description: `Page - ${i + 1}`,
          value: `${i + 1}`,
          label:
            e instanceof MessageEmbed ? e.title ?? "Select Page" : "Select ",
        });
      });
    } else if (Array.isArray(options)) {
      if (options.length < 0) return null;
      option.push(
        ...options
          .slice(0, this.pages.length - 1)
          .map((e, i): MessageSelectOptionData => {
            if (typeof e !== "string" || e !== null)
              throw new DJ_P_Error(
                `Pagination.PageSelection[${i}] : Invalid type provided. Only type string is valid  `
              );
            return {
              value: `${i + 1}`,
              description: `Page - ${i + 1}`,
              label: e ?? "Select",
            };
          })
      );
    } else throw new DJ_P_Error("Invalid Argruments");
    return this.ChunksOfLen(option, 25);
  }
  findBtn(q: string): MessageButton | MessageSelectMenu | undefined {
    const m = this.rows.map((e) => e.components).flat(1);
    const test = m.find((e: MessageActionRowComponent): boolean => {
      return e.customId === q;
    });
    if (!test) return;
    return test;
  }
  vaild({ channel, authorizedUsersId }: authorized) {
    if (!this.pages?.length) throw new DJ_P_Error("No pages Found");
    if (this.pages.length < 0) throw new DJ_P_Error("No page Found ");
    if (!channel) throw new DJ_P_Error("channel not found ");
    if (!(channel instanceof Channel))
      throw new DJ_P_Error("Invalid Argruments Provided ");
    if (channel.isVoice())
      throw new DJ_P_Error("Cannot send message in voice channel ");
    if (!Array.isArray(authorizedUsersId))
      throw new DJ_P_Error("Invalid Argruments Provided ");
  }
  async send(args: authorized) {
    this.vaild(args);
    const sender: Message | null = this.loadingMsg
      ? await args.channel.send(this.loadingMsg)
      : null;
    if (this.reaction) {
      this.reactionArr = this.getButtons(this.showbuttons).emoji;
      // await this.handleReaction(args, sender);
    } else {
      this.buttons = this.getButtons(this.showbuttons).button;
      await this.handleBtn(args, sender);
    }
  }

  private async handleBtn(
    { channel, authorizedUsersId }: authorized,
    message: Message | null
  ) {
    this.rows = this.getRows();
    if (this.PageSelection) {
      var i = 0;
      for (const k of this.PageSelection) {
        i++;
        this.rows.push(
          new MessageActionRow().addComponents(
            new MessageSelectMenu().addOptions(k).setCustomId(`select-${i}`)
          )
        );
      }
    }
    const test = this.findBtn("page");
    test?.setDisabled(true);
    const pageBtn = test instanceof MessageSelectMenu ? null : test;
    const options: WebhookEditMessageOptions = {
      components: this.rows,
      attachments: this.attachments,
    };
    if (typeof this.pages[this.page] === "string") {
      options.content = this.pages[this.page] as string;
      options.embeds = [];
    } else {
      options.embeds = [this.pages[this.page]] as MessageEmbed[];
      options.content = null;
    }
    pageBtn?.setLabel(`Page ${this.page + 1}/${this.pages.length}`);
    this.message = await (message
      ? message.edit(options)
      : channel.send(options as MessageOptions));
    const filter = (
      interaction: MessageComponentInteraction
    ): Promise<boolean> | boolean => {
      return (
        (Object.keys(this.showbuttons)
          .map((e) => e)
          .includes(interaction.customId) ||
          ((this.PageSelection &&
            /^select-(d)/gi.test(interaction.customId)) ??
            false)) &&
        authorizedUsersId.includes(interaction.user.id)
      );
    };
    const collect = this.message.createMessageComponentCollector({
      filter,
      time: this.timeout,
    });
    collect.on("collect", async (interaction: Interaction) => {
      if (!interaction.isButton() && !interaction.isSelectMenu()) return;
      await interaction.deferUpdate();
      let { customId } = interaction;
      switch (customId) {
        case `first`:
          this.page = 0;
          break;
        case `back`:
          this.page = this.page - 1 < 0 ? 0 : this.page - 1;
          break;
        case `forward`:
          this.page =
            this.page + 1 >= this.pages.length
              ? this.pages.length - 1
              : this.page + 1;
          break;
        case `last`:
          this.page = this.pages.length - 1;
          break;
        case `removeBtn`:
          options.components = [];
          collect.stop();
          break;
        case `Mdelete`:
          await interaction.deleteReply().catch(console.error);
          collect.stop();
          return;
        default:
          if (!interaction.isSelectMenu()) break;
          if (/^select-d/gi.test(customId)) {
            const no = parseInt(interaction.values?.[0]);
            this.page = no - 1;
          }
      }

      pageBtn?.setLabel(`Page ${this.page + 1}/${this.pages.length}`);
      if (typeof this.pages[this.page] === "string") {
        options.content = this.pages[this.page] as string;
        options.embeds = [];
      } else {
        options.embeds = [this.pages[this.page]] as MessageEmbed[];
        options.content = null;
      }

      await interaction.editReply(options);
    });
    collect.on("end", async (i) => {
      options.components = [];
      this.message.editable &&
        (await this.message?.edit(options).catch((e) => null));
    });
  }
}