how to remove partial duplication from object of array in typescript/javascript?

What is the best way to filters partial matched object of array in typescript/javascript?
I have one set of object of array that I want to remove the object when value from key ‘name’ is the same

const objArray = [{id: 1, name:{first: 'a', last: 'b'}, phone:123}, {id: 2, name:{first: 'a', last: 'b'}, phone:456}, {id: 3, name:{first: 'c', last: 'd'}, phone:3434}]
// look for return
// [{id: 1, name:{first: 'a', last: 'b'}, phone:123}, {id: 3, name:{first: 'c', last: 'd'}, phone:3434}]

Convert to accordion

I’m new here.

I’m trying to convert my <li> into an accordion in the mobile view.

I actually have something similar to:

<div class="general" id="horizontalTab">
    <div class="list">
        <ul>
            <li class="item1">Item 1</li>
            <li class="item2">Item 2</li>
            <li class="item3">Item 3</li>
        </ul>
    <div>
    <div>
        <div class="item1">Description 1</div>
        <div class="item2">Description 2</div>
        <div class="item3">Description 3</div>
    <div>
<div>

And I have this on the footer.php

<script src="<?php echo get_stylesheet_directory_uri(); ?>/assets/js/jquery.responsiveTabs.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        var $tabs = $('#horizontalTab');
        $tabs.responsiveTabs({
            rotate: false,
            startCollapsed: 'accordion',
            collapsible: 'accordion'
        });

    });
</script>

But it shows me “Uncaught TypeError: oTab is undefined”
So every time I click on the li it displays the related div description.

Now I’d like to convert that into an accordion for the mobile version and moving the description under its <li>.

Any ideas?

I’ve tryied following this: https://www.jqueryhub.com/responsive-tabs-to-accordion-jquery-plugin-responsive-tabs/ but it’s not working 🙁

Thanks!

ReactJS component won’t update after first API call

So I recently started to discover ReactJS. I have a simple Spring Boot api which has a few methods. One of these returns a list of objects. I get these in my frontend by using Axios to make the HTTP call.

export function getItems() {
  const [items, setItems] = useState([]);
  useEffect(async () => {
    await client.get('items').then((result) => {
      setItems(result.data);
    });
  }, []);
  return items;

The items are mapped in a gallery component and shown on screen. Next to this, I have an addItem function which posts an item object obtained through a form to my api.

export async function addPet(newPet) {
      await client.post(
        '/pets',
        newPet,
      );
    }

My AddPet component is loaded inside my Gallery component. The form is shown on the right side of the screen and when I click the “Add Item” button, I want the item to be added and my list of items reloaded to show the newly added item. Right now, I can not get this working in a correct way. If I remove the “[]” from the final part of my useEffect() in my getItems() functions, everything seems to work but in reality the app is making the getItems call over and over again. If I add “[]”, the call is only made once at the start, but will not re-render the gallery component when an item is added. The handleSubmit() for my “Add item” button is as follows:

const handleSubmit = () => {
    const newItem = new Item();
    newItem .name = formValue.name;
    newItem .image = formValue.image;
    newItem .pitemText = formValue.itemText;
    addItem(newItem);
  };

So my question here is: how can I get that gallery component to re-render whenever I add a new item or delete one of the items? I figure I need a way to change the state of the component but I can’t seem to get it done.

Bootstrap modal does not show up after submit

Hello I’m trying to display a bootstrap modal after they select a withdrawal amount and click on submit button which also updates the withdraw row in the database, I tried echo the full bootstrap html but it still blinks and doesn’t stay as it is supposed to be

So far it only blinks and doesn’t stay at all.

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>


<?php
// Include config file
require_once "config.php";
 
// Define variables and initialize with empty values
$withraw = "";
$withraw_err = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
      // Validate Withrawal
    if(empty(trim($_POST["withraw"]))){
        $withraw_err = "Please Choose a Amount.";     
    } else{   
            $withraw = trim($_POST["withraw"]);
            }

    // Check input errors before inserting in database
    if(empty($withraw_err)){
        
        // Prepare an insert statement
        $sql = "UPDATE users SET withraw = (?) WHERE id = 211";

        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_withraw);
            
            // Set parameters
           
            $param_withraw  = $withraw;
           
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
               echo "<script>
         $(window).load(function(){
             $('#myModal').modal('show');
         });
    </script>";
            } else{
                echo "Something went wrong. Please try again later.";
            }

            // Close statement
            mysqli_stmt_close($stmt);
        }
    }
    
    // Close connection
    mysqli_close($link);
}
?>

       <label><h1 class="h1">withraw</h1></label>
        

        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
           
 
          
 


              <div class="form-group <?php echo (!empty($withraw_err)) ? 'has-error' : ''; ?>">
               

                <div class='selectt'><select name="withraw" class="form-control" value="<?php echo $withraw; ?>"><option >Choose Amount</option>
        <option value="500">500</option>
        <option value="1000">1,000</option>
        <option value="1500">1,500</option>
        <option value="2000">2,000</option>
        <option value="2500">2,500</option>
                <option value="3000">3,000</option>
        <option value="3500">3,500</option>

</select>
        
        </div>
                <span class="help-block"><?php echo $withraw_err; ?></span>
            </div>    
        
        

    

          <div class="form-group">
                <button type="submit" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" value="Submit">
                    Withraw <i class='fa fa-check-circle'></i> </button>
                <button type="reset" class="btn btn-default" value="Reset"><i class='fas fa-redo'></i> Reset </button>
            </div>

        </form>
   
   

 <div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title"><img src="loading.svg" class="loaderr"> Pending Approval</h4>
      </div>
      <div class="modal-body">
        <p>Hello User, your request to withdraw has been sent to the Company.
        
        <br>
       <br>
       You will be notified when the withdrawal status has been updated.
      <br>
      <br>
      <font color="red">Note:</font> Do not resubmit a withdrawal request until the next 48hours
        </p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

</div>
    
 

Thank you so much, I’m sorry the code is bulky

How do i make the guesses go down by one in hangman

I have tried to make the guesses go down by one if the word they clicked on dont match the word. but every time i try to do it, it either makes the guesses go down one but then it will also go down when the word matches. and if i try changing the code the guesses will go down by how many words there are left. Like this one

function wordChecker(cell) {

    for (let i = 0; i < word.length; i++) {
        if (word[i] === cell.innerHTML) {

            answerArray[i] = cell.innerHTML
            answer.innerHTML = answerArray.join(" ")
            remainingLetters--
            checkWin()
            console.log(remainingLetters);
            console.log(answerArray);
            break;

        } else {
            guesses.innerHTML--
            console.log(guesses);
        }
    }

}

i thought it could be because of the for loop and even though i make an if outside of the for loop i doesnt work properly.

Is it possible to download a blob after the preview has been opened in a new tab?

I use the following code to download some binary data (a PDF document) and open result in a new tab :

$.ajax({
    url: this.downloadurl,
    xhrFields: {
        responseType: "blob"
    }
})
.done(blob => {
    var url = URL.createObjectURL(blob);

    //open blob in new tab
    window.open(url);
    
    //additionally, download the document
    var a = $("<a>", {
        href: url,
        download: this.filename,
    }).appendTo(document.body);
    a[0].click();
});

It also download the document automatically because I found out that it’s not possible to download it using the download icon in the preview.
Here is the PDF document preview in Chrome. If I click on download icon :

enter image description here

It will give this :

enter image description here

Is there a way to prevent this ?
It looks like the URL can only be used once.

How to render a jsx element by sending it as a prop using react and javascript?

i want to render jsx element by passing it as a prop to a component using react and javascript.

below is my code,

const renderButton = (
    <button>Click me </button>
);

const renderResult = (
    {userPermissions.ADD && isInProgress && renderButton} //error here
); 

<SomeComponent
    renderResult={renderResult}
/>

the problem is with renderResult method. how can i render the renderButton. i think the way i am returning jsx element is not correct.

could someone help me with this. thanks.

Sentry not capturing third party widget crash

I installed the Drift widget on my website, as per instructions.

However, when it crashes, the error doesn’t get captured by Sentry.

It is not filtered out in Sentry, nothing gets sent to Sentry from the front-end.

I tried to search for a solution, but surprisingly it seems people usually have the opposite problem: they are seeing errors from the Intercom widget in their own Sentry dashboard.

Any idea what might be wrong?

How to display array value to dropdown list using PHP?

I want to display this array value in dropdown using PHP with output like this 10:00 AM to 10:30 AM. The array below is the output of slots. I want to display start time and end time per list in dropdown.

$slots = getTimeSlot(30, ’10:00′, ’13:00′);

Array
(
    [1] => Array
        (
            [slot_start_time] => 10:00
            [slot_end_time] => 10:30
        )

    [2] => Array
        (
            [slot_start_time] => 10:30
            [slot_end_time] => 11:00
        )

    [3] => Array
        (
            [slot_start_time] => 11:00
            [slot_end_time] => 11:30
        )

    [4] => Array
        (
            [slot_start_time] => 11:30
            [slot_end_time] => 12:00
        )

    [5] => Array
        (
            [slot_start_time] => 12:00
            [slot_end_time] => 12:30
        )

    [6] => Array
        (
            [slot_start_time] => 12:30
            [slot_end_time] => 13:00
        )

)
<select name="time" id="time">
    <option value=""></option>
</select>

Add deposit payment on the checkout page

I want a code to insert either in the function.php file or in a sniper to add a deposit to the final form-pay total.
the plugin I use does not use all the features of woocommerce it just uses the form-pay checkout page; Please help.

Rental fee per day                    × 1                       €1,250.00

Security deposit fee (not included) ×   1                       €8,000.00

One way fee                           × 1                       €1,000.00

After hours return fee                × 1                       €300.00

Subtotal:                                                      €10,550.00

Total:                                                          €2,550.00

I want the total to be like this

Total:.....

to pay:.....

Balance :....

Best regard

How to efficiently manipulate strings in Javascript?

How do I efficiently make changes to a string in Javascript without creating a new string every time I make a change? The attached code
illustrates this as each “result +=” operation
will generate a new string.

The idea of using a Unit8Array as a work area appears to fail because converting to a string is just as inefficient.

; Use mask to change characters in string to a
; '-' if mask dictates that. 
function maskOutput(input, mask) {
 let result = '';
 for (let i=0; i < input.length; i++){
    if (mask.charAt(i) === 'X') {
      result += '-';
    } else {
       result += input.charAt(i);
    }
 }
 return result;
}

check if urls have the same origin

I have a function that runs before every API request to check if the request is from a valid origin.

I have an array of valid origins

const whitelist = [ 'a.com', 'b.co.uk' ]

const validOrigin = str => {
    const url = new URL( str )
    return whitelist.includes( url.host )
}

console.log(validOrigin('https://www.a.com'))

It returns false because of the www. I dont want to just add a copy with www. to the array of valid origins. I would like a way that covers this and everything else thats unexpected.

Log keypress to console JS

I have this jQuery code:

$(`#searchbar`).on(`keyup`, function(){
      var value = $(this).val()
      console.log("Value:", value)
})

Which logs the text in the input in the console.

For example if you write test the console will look like this:

Value: t
Value: te
Value: tes
Value: test

Is this possible to do with just pure JS, no jQuery?

Is there a way to get autocomplete for .proto JavaScript generated code?

I’ve written a simple .proto file

syntax = "proto3";

message Event {
  optional string name = 1;
}

I’ve downloaded the protoc linux compiler (protoc-3.19.3-linux-x86_64.zip) and installed it in my local machine outside of the project’s folder.

Then I installed the core runtime dependency with

$ npm i google-protobuf

My package.json shows:

"google-protobuf": "^3.19.3",

I then ran this line to generate the JS code from the .proto file

$ protoc –js_out=import_style=commonjs,binary:. protos/event.proto

It outputs some generated code that I can import with

const Schema = require("./protos/event_pb");

by inspecting Schema.Event I can see that my prop .name is in there, but I can’t get any autocomplete going. Is there a way to achieve this?