Result won’t update VAR

I am trying to run a query, inside AXIOS which gets data from a 3rd party URL. Then uses some of that data to search our mongoDB database.

However it seems it won’t update var total = 0

While the query below does function correctly, the return result won’t allow me to set that it to the query.

 Promise.all(arr.forEach( async (id,index) => {
                    //(CODE REMOVED JUST TO GET THIS FUNCTION TO WORK)
                       
                       const search = await geoLocation.find({
                         'location': {
                           '$geoWithin': {
                             '$box': [
                               [-35.2418503, -13.5076852], [112.8656697, 129.0020486]
                             ]
                           }
                         }}).toArray();
                         total = search.length;
                        
                     }));

See the full code below


    
    var array = [];
    var pointarray = []
    var total = 0; 
                   
    areas.forEach((id,index) => {
      if(id.type == "Point"){
        pointarray[index] = "N"+id.id;
    }else{
        array[index] = "R"+id.id;
    }
    });



            var arraySearch = "https://nominatim.openstreetmap.org/lookup?osm_ids="+array.toString()+"&polygon_geojson=1&bbox=1&format=json";
            var pointSearch = "https://nominatim.openstreetmap.org/lookup?osm_ids="+pointarray.toString()+"&polygon_geojson=1&bbox=0&format=json"

            const requestOne = axios.get(arraySearch);
            const requestTwo = axios.get(pointSearch);
            

            axios.all([requestOne, requestTwo])
                .then(axios.spread((...responses) => {
                  const responseOne = responses[0]
                  const responseTwo = responses[1]

                 
                  /*
                    process the responses and return in an array accordingly.
                  */
                  return [
                      responseOne.data,
                      responseTwo.data,
                      
                  ];
                }))
                .then(arr => {
                    Promise.all(arr.forEach( async (id,index) => {
                      //const middleIndex = id[index].boundingbox.length / 2;
                      //const firstHalf = id[index].boundingbox.splice(0, middleIndex);   
                      //const secondHalf = id[index].boundingbox.splice(-middleIndex);
                      //res.send(secondHalf[0]);
                       const query = [{
                         $match: {
                             location: {
                                 $geoWithin: {$box:[[Number(firstHalf[0]),Number(firstHalf[1])],[Number(secondHalf[0]),Number(secondHalf[1])]]
                                 }
                               }
                             }
                         },{
                           $count: 'id'
                       }]
                       
                       const search = await geoLocation.find({
                         'location': {
                           '$geoWithin': {
                             '$box': [
                               [-35.2418503, -13.5076852], [112.8656697, 129.0020486]
                             ]
                           }
                         }}).toArray();
                         total = search.length;
                        // total = search.length;
                         // const search = geoLocation.aggregate(query).toArray.length;
                     
                     }));
                     
                    
              })
                .catch(errors => {
                    console.log("ERRORS", errors);
                })
                .then(function () {
                 res.send(total);
                  
              });

    

react.js push new matched values of array into existing one by js map method

I’m coding to make a web view with API data to show up in the window but having some problems. Can anyone help me with this prob?

maybe I’m not good at speaking English for you to understand, I made some pictures what I want to make.

First, I have an array like this

const arr1 = [
  {name: 'AAA', no: 23},
  {name: 'BBB', no: 42},
  {name: 'CCC', no: 33},
  {name: 'DDD', no: 90},
  {name: 'EEE', no: 101},
  {name: 'FFF', no: 10},
]

I mapped it name for div h2 title, and no to p tag.
Here is the current conditions
enter image description here

Now I make a new array to add more p tags into div, and the array has a shape like this.

const arr2 = [
  {letter: 'text1', no: 90},
  {letter: 'text2', no: 90},
  {letter: 'text3', no: 23},
  {letter: 'text4', no: 42},
  {letter: 'text5', no: 101},
  {letter: 'text6', no: 10},
  {letter: 'text7', no: 90},
  {letter: 'text8', no: 90},
]

what I exactly want to make is, find the elements that arr1.no === arr2.no and add right after the p tag like this picture.

enter image description here

what I want;

  1. if arr2 has not number corresponding to arr1, then go on the next one
  2. if arr2 has multiple elements to one of arr1’s no, then it should be added right behind the p tag.

So I coded like this,

arr1.map((c, i) => {  
  arr2.map((v, j) => {
      if (c.no === v.no) {
          test.innerText = 'this title has letter: ' + c.no;
      }
  })
})

I knew I have to make 2 maps to match those 2 arrays, but this does not work.
all ‘this title has letter’ returns same number.
Can anyone please let me know what I missed?

Javascript Split coordinates to list

I have a string which includes my coordinates list.
I want to convert this string;

var  myString =   "(38.35870116756209, 38.27089903372614),(38.3339292947434, 38.2743322612652),(38.33944984782068, 38.3017980815777),(38.35829734627614, 38.297678208530826)"

to this;

const polygonCoords = [

                    { lat: 38.35870116756209, lng: 38.27089903372614 },
                    { lat: 38.3339292947434, lng: 38.2743322612652 },
                    { lat: 38.33944984782068, lng: 38.3017980815777 },
                    { lat: 38.35829734627614, lng: 38.297678208530826 },
                    { lat: 38.35870116756209, lng: 38.27089903372614 },//this is the first again
                ];

Make the Javascript includes() method return items with hyphen

I am using the javascript includes() method to filter an array of object that looks like this;

  const names = [
    {name: 'Rose-mary Thompson', age: 30},
    {name: 'Rose mary Samuel', age: 30},
    {name: 'John-Doe Jackson', age: 30},
    {name: 'John Doe Philips', age: 30},
  ]

if I search for ‘Rose mary’, I want the result to also include ‘Rose-mary’.
I don’t want the user to have to type hyphen(-) before the names with – come out in the search result.

This is my code;

let searchQuery = 'Rose mary'
let filteredResults = []

const searchItems = () => {
    if (searchQuery.length > 1) {
        const results = names.filter((name) => {
            return name.name.toLowerCase().includes(searchQuery.toLowerCase());
          });
        filteredResults = results
    }  
}

Please how do I achieve this?

To create a button for next page

How to specify the button that which next page should I open after veryfiyng two if statement.
Like if we have two values department and shift and a user select IT department and night shift then the button should open the same detailed page after click get details button.
And if the user select ME department and Morning shift then the same button should open the matched details.

In javascript how to replace elements of an array to it’s corresponding values in another object?

Javascript

\ I have the mapping of abbreviation and full name as follow:

object = {“TSLA”:”TESLA INC.”,”GOOG”:”GOOGLE INC.”,”APPL”:”APPLE INC.”,”AMZN”:”AMAZON CORPORATION”, “MSFT”:”MICROSOFT CORPORATION”}

\ as an output of function i get the following array:

array = [“AMZN”,”APPL”]

\ I want to display the values of the associated keys as follows:

output_array = [“AMAZON CORPORATION”, “APPLE INC.”]

\ Note that, the actual object has more key: value pairs

Using IndexOf() I can replace one value. However, I believe there must be a way of mapping the array elements to replace the values at once.

Since I am new to JS, I would appreciate any suggestion.

I have a Cargo run error, on rocket_cors method

I’m trying to get my rust rocket app working through cargo run

use rocket::http::Method;

fn make_cors() -> Cors {
  let allowed_origins = AllowedOrigins::some_exact(&[ // 4.
    "http://localhost:3000",
    "http://127.0.0.1:3000",
    "http://localhost:8000",
    "http://0.0.0.0:8000",
  ]);
  CorsOptions { // 5.
    allowed_origins,
    allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(), // 1.
    allowed_headers: AllowedHeaders::some(&[
      "Authorization",
      "Accept",
      "Access-Control-Allow-Origin", // 6.
    ]),
    allow_credentials: true,
    ..Default::default()
  }.to_cors().expect("error while building CORS")
}

The following error is bugging me:

the trait bound `rocket_cors::Method: std::convert::From<rocket::http::Method>` is not satisfied
the trait `std::convert::From<rocket::http::Method>` is not implemented for `rocket_cors::Method`

how to provide default value while destructing interfaces inside interfaces in typescript?

what i’m trying to accomplish here is to be able to use the function in a way that if:

you provided arguments it works with the provided arguments, yet
if arguments were not provided it would use the default values.

the problem i have is that the following code, has no typescript error but in runtime when the function is called like testingInterfacesFunction() i get this error:

Cannot read properties of undefined (reading ‘title’)

interface Success {
  onSuccess: (x: any) => void | null
  successTitle: string
  successSubtitle: string
  successIcon: "success" | "info" | "error" | "question" | "warning"
}
interface Denial {
  onDenied: (x: any) => void | null
  denialTitle: string
  denialSubtitle: string
  denyIcon: "success" | "info" | "error" | "question" | "warning"
}
interface Dismiss {
  onDismissed: (x: any) => void
  dismissTitle: string
  dismissSubtitle: string
  dismissIcon: "success" | "info" | "error" | "question" | "warning"
}
interface Extra {
  confirmButton: string
  cancelButton: string
  focus: boolean
}
interface Params {
  title: string
  subTitle: string
  icon: "success" | "info" | "error" | "question" | "warning"
  success: Success
  deny: Denial
  dismiss: Dismiss
  extra: Extra
}

const testingInterfacesFunction = (params: Params) => {
  const {
    title = "",
    subTitle = "",
    icon = "question",
    success: { onSuccess = null, successTitle = "", successSubtitle = "", successIcon = "success" },
    deny: { onDenied = null, denialTitle = "", denialSubtitle = "", denyIcon = "error" },
    dismiss: { onDismissed = null, dismissTitle = "", dismissSubtitle = "", dismissIcon = "error" },
    extra: { confirmButton = "done", cancelButton = "cancel", focus = false }
  } = params

... the body of the function ...

}

i even tried to console.log the title, but seems like the code doesn’t react to the body of the function at all…

all i want to do is to have a function that optionally accepts these properties while if it’s not provided it uses the defaults, how can i accomplish such a thing?

Call API have duplicate Data and output 500 arry

i need some help in my code

if see the visit api url you will see Large Data duplicated

const url = 'https://raw.githubusercontent.com/globaldothealth/monkeypox/main/latest.json';



async function getData() {
    const response = await fetch(url);
    const data = await response.json();
    console.log(data);

How we Can Merge all data and Sum it like to show have 500 infected named Confirmed And SUSPACKTED
AND SHOW IT BY Numbar

Why does the if statement ignore the expression while removing DOM nodes? [duplicate]

I’ve tried all sorts of solutions to index a array and remove elements that match a regex. The solution I ended up with should work, as it doesn’t skip loop iterations due to the array length changing, which is the problem I had before. However now it just seems to ignore my if statement.

   const iframes = Array.from(document.getElementsByTagName("iframe")).filter(frame => frame.getAttribute("src") == "/domain/to/iframe");
   const idoc = iframes.length === 1 ? iframes[0].contentWindow.document : document;
   const regex = /.*TextGoesHere*/sig;
   var msgs = idoc.getElementsByClassName("message");
   msgs = Array.from(msgs);
   while (msgs.length > 0) {
    removal = msgs.pop(msgs.length);
    if (regex.test(removal.innerHTML)) {
        removal.remove();
    } else {
        console.log(regex.test(removal.innerHTML));
    }
   }

Output:

false
false
true
true
false
false

.get() method failing in Jquery

I am trying to access and style the different objects inside a jQuery object by using .get(); and I have been successful in simply accessing the individual objects but unable to perform operations like adding css or classes to those individual elements. I also tried to use [] to access and style; but access is again a success while I am not being able to style that selected element. Why is this happening?

my script using .get() =>

$(()=>{
  $('button').click(function(event){
    $(".box div").toggleClass('color');
  });
});
.box{
  font-size: 0px;
  width: min-content;
}

.color{
  display: inline-block;
  width: 20px;
  height: 20px;
  background-color: red;
  border: 1px solid white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
  <div></div>
  <div></div>
  <div></div>
</div>

<button>click</button>

TypeError: $(…).get(…).toggleClass is not a function

Why is this message coming? How to resolve this and get specific index element from a jQuery Object?

How to apply onClick in the input

As you can this is a string js and I want to use onClick on the input whose view is being toggled by selecting the boolean value edit. Please suggest how to use onchnage here.

Already tried normal HTML onchange (not working)

onchange="${onchnage}"

Pls, suggest if you happen to know the answer.

    export const DefaultNode = (d, selectedNodeIds, edit, fomatOptions, inputOnclick) => {
    
    const mainData = d.data.data
  
    return `<div style='background:${selectedNodeIds.length!==0 ? (selectedNodeIds.includes(d.data.id) ? `rgba(${ fomatOptions.nodeBg.r }, ${ fomatOptions.nodeBg.g }, ${ fomatOptions.nodeBg.b }, ${ fomatOptions.nodeBg.a })`: "#fff"): `rgba(${ fomatOptions.nodeBg.r }, ${ fomatOptions.nodeBg.g }, ${ fomatOptions.nodeBg.b }, ${ fomatOptions.nodeBg.a })`}; 
        color:${selectedNodeIds.length!==0 ?(selectedNodeIds.includes(d.data.id) ?`rgba(${ fomatOptions.textColor.r }, ${ fomatOptions.textColor.g }, ${ fomatOptions.textColor.b }, ${ fomatOptions.textColor.a })`:'#000'): `rgba(${ fomatOptions.textColor.r }, ${ fomatOptions.textColor.g }, ${ fomatOptions.textColor.b }, ${ fomatOptions.textColor.a })`}'
                    
                    
                    class=${`"w-[250px] p-3  rounded-[15px] relative border-[3px] h-[140px] ${selectedNodeIds.includes(d.data.id)? 'drop-shadow-md' :"shadow"} ${ selectedNodeIds.includes(d.data.id) && fomatOptions.fontFamily.value}"`}>
            <div class='flex justify-between  w-full  '>
            <div class="">
                ${edit? `<input onclick='${inputOnclick}' class="fullName text-[13px] font-semibold" value="${mainData.name}"/>` : `<div class=" text-[13px] font-semibold">${mainData.name} </div>`}
                <div class=" text-[11px] opacity-70 mt-0.5 font-medium">${mainData.position } </div>
                <div class='mt-2'>
                    <div class=" text-[11px] opacity-70 mt-0.5 font-medium">${mainData.email } </div>
                    <div class=" text-[11px] opacity-70 mt-0.5 font-medium">${mainData.phone } </div>
                </div>

            </div>
            <img class='w-10 h-10 mr-2 rounded-[10px]' src=${mainData.imgUrl} />
    </div>
    <div class='flex pt-4 justify-between items-center'>
        <p class='text-[10px] font-medium uppercase bg-theme-gray px-2 text-black rounded-full py-0.5'>${mainData.department}</p>
        <p class='text-[10px] font-medium uppercase mr-2'>${mainData.location}</p>
    </div>
    ${((selectedNodeIds.includes(d.data.id))) ? `<div class="absolute left-4 -top-5 font-semibold text-[10px] p-1 bg-gray-400 text-white rounded-t-md">
        Selected
    </div>`: `<p></p>`}
</div>`
}

How to filter useState hook Array and push & pull data to that array?

I am searching for filter React useState hook array. Not getting any answer. Please help me.

I define useState string array-

const [filterBrand, setFilterBrand] = useState<string[]>([]);

Here is my function for filtering this array and push, pull data-

const brandHandler = (item: string) => {
    //Here I need if filterBrand already have the 
      item then remove it and update the state, 
      else add the item to this array and update 
      the state
}

Here I need to check if item already have in filterBrand. then remove it from filterBrand and update the State.
Else I need to add the item to filterBrand and update the State

I already tried it-

const brandHandler = (item: string) => {
    const items: string[] = [...filterBrand];
    if (!filterBrand.includes(item)) {
        items.push(item)
    } else {
        return items.filter(f => f !== item)
    }
    setFilterBrand(prevState => ({ ...prevState, ...items }));
}

But getting this error-

Invalid attempt to spread non-iterable instance.nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method