reconstruct an array in JS [duplicate]

How can I reconstruct the array1 to the array2. Could you please help me using map/reduce.
Thank you very much for your helps!

const array1 = [
{Count: 35,
Items: [
{Id:1, Category:'Account', Count:10, class:'A'},
{Id:2, Category:'Account', Count:5, class:'B'},
{Id:3, Category:'Account', Count:20, class:'B'},
]},
{Count: 75,
Items: [
{Id:1, Category:'Logout', Count:25, class:'A'},
{Id:2, Category:'Logout', Count:30, class:'B'},
{Id:3, Category:'Logout', Count:20, class:'C'},
]},
{Count: 85,
Items: [
{Id:1, Category:'Login', Count:10, class:'A'},
{Id:2, Category:'Login', Count:25, class:'B'},
{Id:3, Category:'Login', Count:50, class:'C'},
]}
]

const array2 = [
{name: 'Account', data: [10,5,20]},
{name: 'Logout', data: [25,30,20]},
{name: 'Login', data: [10,25,50]},
]

carousel is not working properly for second and third iteration in react js

I am creating a project in reactjs , where i am rendering carousel in loop, and carousel of first iteration is working perfectly but for other iteration’s it’s not.
can anybody suggest what is the wrong i am doing with the carousel.
this is my codesandbox link :- https://codesandbox.io/s/nice-heyrovsky-8yucf?file=/src/App.js

this is not the actual project so please ignore the empty data and other components.just look at the Prompts and card components.

CSS Float Question (Strange behaviors found)

Dears,

Below is my simple float program and I also attach a picture of the result. My question is: When the width in class “two” is 300px, the div 2 is moved next to the floated div 1, this is also my expectation. However, when i changed the width in class “two” from 300px to 200px, div 2 is kept under div 1, and div 3 is moved to overlap with div 2 (see the attached picture) Why? enter image description here

<html>`
<head>
<style>
.one{
    background: yellow;
    width: 200px;
    height: 50px;
    text-align: center; 
    box-shadow: inset 0 0 10px #000;
    Float: left;
    }

.two {
    background: rgb(55, 0, 255);
    width: 300px;
    height: 50px;
    text-align: center; 
    box-shadow: inset 0 0 10px #000;  
  }

.three {
    background: rgb(255, 0, 76);
    width: 200px;
    height: 50px;
    text-align: center; 
    box-shadow: inset 0 0 10px #000;
   }
 </style>
 </head>
 <body>
    <div class = "one">1</div>
    <div class = "two">2</div>
    <div class = "three">3</div>
 </body>
 </html>

Regex to clean a string and left only digits and the first dot in javascript

I want to replace with a regex any non digit character and the dots after the first one so

“–r43dsd.32.32” would be 43.3232

“–r4.3dsd.32.3.2” would be 4.33232

“–r43dsd.32.3.2” would be 43.3232

I tried this

.replace(/[^0-9.]/g, '')

but I don’t know how to remove the dots with replace and a regex. I read that I should use regex look ahead but I did not understand how to do it.

Is this achievable with only a regex and replace? I also created a function but I want to do it in a more clean way with a regex.

How to pass array of structs as argument on etherscan (tuple[])?

I’m trying to pass the format of array of structs as argument on smart contract write function on etherscan,

This is solidity example:

Info[] public info;

struct Info { 
    address userAddress;
    uint256 amount;   
    bool active; 
} 

enter image description here
Javascript example:

const data = [{0x0000, 10000000000, false},{0x11111, 20000000000, true}]

Can anyone convert this data example to tuple[] and provide it?
Thanks in advance

What is the easiest way to filter an object in javascript? [duplicate]

Yes, I know, there is already a question about how to filter objects in javascript, but look, I’m not asking how to do it, I’m asking about what would be the easiest way, the one which a noob like me could remember.

Before ask I spent a little time and after some tests I came up with theses solutions. They are examples but I cannot think about something better by now:

function queryHandlerOne(query: any) {
  const fields = ["name", "featured", "price", "company", "rating"];
  
  const entries = Object
    .entries(query)
    .filter(([key, _]) => fields.includes(key));

  return Object.fromEntries(entries);  
}
function queryHandlerTwo(query: any) {
  const fields = ["name", "featured", "price", "company", "rating"];

  const entries = Object
    .keys(query)
    .filter(key => fields.includes(key))
    .reduce((acc, key) => {
      acc[key] = query[key];
      return acc;
    }, {} as any);

  return entries;
}
function queryHandlerThree(query: any) {
  const fields = ["name", "featured", "price", "company", "rating"];

  const result = Object
    .keys(query)
    .filter(key => fields.includes(key))
    .map(key => [key, query[key]] as [string, any]);

  return Object.fromEntries(result);
}
function queryHandlerFour(query: any) {
  const fields = ["name", "featured", "price", "company", "rating"];
  const result = {};

  Object
    .keys(query)
    .filter(key => fields.includes(key))
    .forEach(key => Object.assign(result, { [key]: query[key] }));

  return result;
}

The exactly same idea puts a rectangle along the centerline of it though cannot put an image in the right place, how do I fix it?

I’m trying to draw some kind of a “ray” with Phaser 3.

I started the experiment with a simple rectangle to represent the ray. Here is the code.

  this.add.circle(90, 290, 10, 0xf00000);
  this.add.circle(290, 190, 10, 0xf00000);
  let angle = Phaser.Math.Angle.Between(90, 290, 290, 190)
  let reference = this.add.rectangle(90, 290, 600, 5, 0x00f000).setOrigin(0);
  reference.rotation = angle

The line doesn’t start at the center of its starting point.

enter image description here

I know the reason is Phaser draws the line (actually rectangle) starting top-left 90, 290 where the centerline of the rectangle is supposed to start at.

To fix it, I just need to change y of the top-left

let reference = this.add.rectangle(90, 290-5/2, 600, 5, 0x00f000).setOrigin(0);

where the 5 in 5/2 represents the height of the green rectangle.

And then I got what I want

enter image description here

However, things got complicated when I try to move something along the “ray”.

Here is the code.

var game = new Phaser.Game({
  scene: {
    preload: preload,
    create: create
  }
});

function preload() {
  this.load.path = 'https://raw.githubusercontent.com/liyi93319/phaser3_rpg/main/part1/assets/';
  this.load.atlas('bolt', 'bolt_atlas.png', 'bolt_atlas.json');
}

function create() {
  this.add.circle(90, 290, 10, 0xf00000);
  this.add.circle(290, 190, 10, 0xf00000);
  let angle = Phaser.Math.Angle.Between(90, 290, 290, 190)
  let reference = this.add.rectangle(90, 290 - 5 / 2, 600, 5, 0x00f000).setOrigin(0);
  reference.rotation = angle
  
  let bolt = this.add.sprite(90, 290-76/2, 'bolt', 'bolt_strike_0002').setOrigin(0);
  bolt.rotation = angle;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/phaser.js"></script>

I just added 2 lines of code based on the previously working code, with the same idea

  let bolt = this.add.sprite(90, 290-76/2, 'bolt', 'bolt_strike_0002').setOrigin(0);
  bolt.rotation = angle;

the 76 in 76/2 represents the height of the bolt (rectangle) I put.

290 represents the y coordinate of the center of the starting point.

The exactly same idea puts the green rectangle along the centerline of it though cannot put the bolt in the right place (along the centerline of the green rectangle), why is that? What am I missing?

enter image description here

Scroll to bottom of HTML page only after dom finishes repainting

I have a function that I want to add a border to the bottom of the page, and then I want to scroll all the way down on the page.

here is my html for it

<div id="bottom-border></div>

Then with JavaScript I am essentially doing this to it

<div id="bottom-border" style="margin-bottom: 10rem;"></div>

after I added the border, then I want to scroll all the way down to then end of the page. Here is how I am doing all of this from JavaScript

        let bottomBorder = document.getElementById('bottom-border');
        bottomBorder.style.marginBottom = '10rem';
        window.scrollTo({top: document.body.scrollHeight, behavior: 'smooth'});

The problem is that it only scrolls down half way because the browser tries to scroll to the bottom while the browser is adding the margin-bottom, so the page only scrolls down half way.

I can do something like this, but I think this is a crummy way of doing it

        let bottomBorder = document.getElementById('bottom-border');
        bottomBorder.style.marginBottom = '10rem';

        let mobileKeyboardStyleSheet = document.getElementById('mobileKeyboardCSS')
        mobileKeyboardStyleSheet.disabled = false;

        setTimeout(() => {
            window.scrollTo({top: document.body.scrollHeight, behavior: 'smooth'});
        }, 1000);

That essentially waits a second before the browser finishes repainting it before trying to scroll down. However, this version gives a bad animation to the end user and it is not always reliable because some browsers take 0.5 seconds to paint and some browsers take 5 seconds to repaint.

I think it would be best if I could tell the browser to:

“do this code, and after it is finished being painted, then do this part of the code”

but I am unsure of how to do that.

Please let me know, thank you!

Remove First and Last Double Quote From JSON Array

Here i have one big array that has multiple arrays inside. I need to remove double quotes from each array. I tried all different methods to pull out quotes but none seem to work.

Current code produces this result:

[
  ["1,jone,matt,ny,none,doctor"],
  ["2,maria,lura,nj,some,engineer"],
  ["3,paul,kirk,la,none,artist"]
]
    const storeArray = [];

    for(var i = 0; i < results.length; i++) {

      var finalArray = results[i].id + "," + results[i].name + "," + results[i].lastname + "," + results[i].address + "," + results[i].status + "," + results[i].about;

      storeArray.push([finalArray]);
    }

    res.send(storeArray);

Javascript: Creating dictionary array using variables for keys and values

I am trying to create a dictionary from some lists using the .push() method.

The result I am trying to achieve is:

{
  "departTo": {
    1: 1.159,
    2: 4.156,
    3: 9.185,
    3: 10.158,
    4: 2.158
  },
  "departTo": {
    1: 2.586,
    2: 5.518,
    3: 11.584,
    3: 7.819,
    4: 3.991
  }
}

Below is a sample of code of what I am trying to do:

console.group("Running Script 1...");

var select_array = [];
var arrive_from, info

var selection_type = ["departTo", "arriveFrom"];
var data_lists_depart = [[1, 1.159], [2, 4.156], [3, 9.185], [4, 10.158], [5, 2.158]];
var data_lists_arrive = [[1, 2.586], [2, 5.518], [3, 11.584], [4, 7.819], [5, 3.991]];

selection_type.forEach(function (selection, i) {
    console.log("selection", i + ": ", selection);
    if (selection === "departTo") data_lists = data_lists_depart;
    else if (selection === "arriveFrom") data_lists = data_lists_arrive;
    data_lists.forEach(function (data_list, ii) {
        console.log("   data_list", ii + ": ", data_list);
        key = data_list[0];
        val = data_list[1];
        select_array.push({selection: {key: val}});
    })
})
console.log("select_array: ", select_array);

console.groupEnd("Running Script 1...");

The result I am getting from the above code is:

[
  {"selection": {"key": 1.159}}, 
  {"selection": {"key": 4.156}}, 
  {"selection": {"key": 9.185}}, 
  {"selection": {"key": 10.158}}, 
  {"selection": {"key": 2.158}}, 
  {"selection": {"key": 2.586}}, 
  {"selection": {"key": 5.518}}, 
  {"selection": {"key": 11.584}}, 
  {"selection": {"key": 7.819}}, 
  {"selection": {"key": 3.991}}
]

Any assistance in getting this into the format I need will be greatly appreciated.
Thank you.

splice() is not emptying the array

Below code should return empty array but it is returning Banana,Banana,Banana

const fruits = ["Banana", "Banana", "Banana", "Banana", "Banana", "Banana"];

fruits.map((ele) => {
  if (ele === "Banana") {
    fruits.splice(0, 1)
  }
})

document.getElementById("demo").innerHTML = fruits;
<div id="demo"></div>

Component re-render on state change not happening

I have a react app similar to what is shown in this codesandbox link https://codesandbox.io/s/eatery-v1691

Clicking the Menu at the bottom center of the page renders the MenuFilter component.

The MenuFilter component in turn uses a checkbox component to render several check boxes & the checked status of these checkboxes depends on the selectedMeals prop that I pass to the MenuFilter in app.tsx.

I read that when the state is passed as a prop, the re-rendering happens as soon as the state changes but this is not happening.

The selectedMeals state is initialized with allItems and then managed such that when any other items is click, that items is set & allItems and these individual items can be several at once. The state management works fine but the checkbox is not getting updated based on the state!

If you however, click cancel (ok button does not do anything yet) & then click Menu button again, only the values in the selectedMeals prop are rendered.

See the video here (https://youtu.be/Zmfc0MQGaIU this is the full app, codesandbox app is representation of this but not the same) where the state change (allItems gets removed & when allItems is checked other items get removed) works perfectly but the check boxes are not re-rendering appropriately

What am I doing wrong & more importantly how do I get the result I want?

I initially put the question here re-render as soon as the state is changed but there was no sandbox for it & since the sandbox is different from what I put in that question, I created a new question. THanks.

Is there a remote DOM manipulation library like drab for elixir but language-agnostic? [closed]

Drab is a library that elixir phoenix liveview uses to remotely control the DOM in the browser. Looking through their code, it seems to contain a javascript library for making the connection to the backend and accepting events. It seems to be completely tied to elixir though, it even uses elixir’s templates to inject values into the javascript code.

So since drab isn’t really an option here, is there another frontend library that lets you control the browser dom remotely through websockets without a reliance on elixir?