Reduce array based on common values on object level

I have an array such as

let array = [
    {
        id: 1,
        name: "Name A",
        expenseAmount: 100
    },
    {
        id: 1,
        name: "Name A",
        expenseAmount: 50
    },
    {
        id: 3,
        name: "Name B",
        expenseAmount: 10
    },
    {
        id: 3,
        name: "Name B",
        expenseAmount: 20
    }
];

And I am looking for a solution, which condenses that array in such a manner, that all objects with the same id and name get summed by their expenseAmount, so that it results in:

let array_goal = [
    {
        id: 1,
        name: "Name A",
        expenseAmount: 150
    },
    {
        id: 3,
        name: "Name B",
        expenseAmount: 30
    }
];

Could you please help? Thanks!

How can I open an Image file using fs in NodeJS?

In my current codes, it does only can read a text file, How can I make an Image (base64) file opened with Photos Application (Windows)? Is there any chance to do that? If it’s impossible, please let me know!

const fs = require('fs')

fs.readFile('./Test/a.txt', 'utf8' , (err, data) => {
    if (err) {
      console.error(err)
      return
    }
    console.log(data)
    return
})

Node.appendChild method is not working in a for loop Javascript

I have an array filled with script elements, I want to loop over them and add them to document with appendChild methods, but even though I can see the added scripts in the inspector tab of the developer console, the scripts are not running (
for example, scripts have console.logs inside but they’re not logging anything. Basically, scripts are not working
).
Here’s the code :

for (let i = 0; i < scriptsToBeAdded.length; i++) {
    let current = scriptsToBeAdded[i];
    let clone = current.cloneNode(true);
    document.body.appendChild(clone);
}

Round number with lots of decimal places in Javascript

I have a number with an extreme amount of decimal places.

1.5583255870000002e+36

I’m struggling to find a good way to round this down to 2 decimal places using JavaScript.

I’ve tried a few variations using parseFloat() Math.round() and .toFixed().

Do I need to use Math.js?

Any other tips?

Thanks,

MongoServerError: Limit value must be non-negative

I’m stuck when I get an error like this, I’ve been looking everywhere for a solution but haven’t gotten any results. Please help me. thank you

Product.js “Routes”

router.get("/products/total/", productsCount)

Product.js “Controller”

exports.productsCount = async (req, res) => {
  let total = await Product.find({}).limit(0).estimatedDocumentCount().exec();
  res.json(total);
}

My error:

enter image description here

Move a page up based on input Click Event in Angular

I implemented NPM Onscreen keyboard in my angular application. Its working good.but i have some issue while i choose the input from bottom of the page. the input is not visible bcz keyboard come over the input. so i need to do a scroll up or create empty space in bottom of the page while i do a click event. how to achieve this thing? any other suggestion?

here am providing a stackblitz url for ur reference:

https://stackblitz.com/edit/onscreen-keyboard-qfg8n4?file=src%2Fkeyboard%2Fkeyboard.component.css

Can I pass props to a React Component from a general function? [duplicate]

   import B from './B.js'; 
   const Test = () => {
      
      async function getResults() {
        await axios
          .get(`http://localhost:2000/?url=${link}`)
          .then((response) => {
            <B data={response.data} />
          });
      }
      return (
        <>
          <div> 
           <button onClick={getResults}> Click </button>
         </div>
        </>
          )

I was trying to pass the axios data as props to my component B. But in console I got undefined value. How to solve this issue. Should I pass the props inside the return area of the Test Component only?

React app pdf link not opening in the swift webview

 <div>
        <a href="https://chat-app-pathum.web.app/pdf/test.pdf" target="_blank" rel="noopener noreferrer">
          chat app
        </a>
      </div>
      <div>
        <a href="/pdf/test.pdf" target="_blank" rel="noopener noreferrer">
          sample link
        </a>
      </div>
      <div>
        <a
          href="http://www.africau.edu/images/default/sample.pdf"
          target="_blank"
          rel="noopener noreferrer"
        >
          hardcoded pdf
        </a>
      </div>

I have a react component with these three links.
test.pdf file is saved in the public/pdf folder and the app is hosted in the domain name of https://chat-app-pathum.web.app

For the first link, I gave an absolute path.
The second link I gave relative path.
The third one is from a different domain name and I gave an absolute path.

All these things are working fine in the web browser. But in the IOS webview (Native mobile app runs the web app in a browser) only the third link opens the document, the other two have no response when I click on top of the link.

How can I fix this at React code level?

This is the link I use
https://chat-app-pathum.web.app

How to get the index of the table into columns array in antd table

I am using antd table for displaying dynamic multiple tables in a react app by mapping a array and rendering the table inside of a collapse of antd
Code: –

import { Button, Input, Table, Collapse } from "antd";
import React, { useState } from "react";

export default function LogbookForm() {
  const { Panel } = Collapse;
  const [data, setdata] = useState([
    {
      section_name: "XYZ",
      details: [
        {
          id: 1,
          name: "c++",
          goals: 6,
          assists: 10,
        },
        {
          id: 2,
          name: "python",
          goals: 6,
          assists: 10,
        },
        {
          id: 3,
          name: "native",
          goals: 6,
          assists: 10,
        },
        {
          id: 4,
          name: "react",
          goals: 6,
          assists: 10,
        },
        {
          id: 5,
          name: "java",
          goals: 6,
          assists: 10,
        },
        {
          id: 6,
          name: "javs script",
          goals: 6,
          assists: 10,
        },
      ],
    },
    {
      section_name: "ABC",
      details: [
        {
          id: 1,
          name: "c++",
          goals: 6,
          assists: 10,
        },
        {
          id: 2,
          name: "python",
          goals: 6,
          assists: 10,
        },
      ],
    },
  ]);
  console.log(data);
  const [tableData, setTableData] = useState([
    {
      id: 1,
      name: "c++",
      goals: 6,
      assists: 10,
    },
    {
      id: 2,
      name: "python",
      goals: 6,
      assists: 10,
    },
    {
      id: 3,
      name: "native",
      goals: 6,
      assists: 10,
    },
    {
      id: 4,
      name: "react",
      goals: 6,
      assists: 10,
    },
    {
      id: 5,
      name: "java",
      goals: 6,
      assists: 10,
    },
    {
      id: 6,
      name: "javs script",
      goals: 6,
      assists: 10,
    },
  ]);
  const onInputChange = (key, index, record, text, i) => (e) => {
    console.log(key, index, record, text, i, e);
    const newData = [...tableData];
    newData[index][key] = e.target.value;
    setTableData(newData);
  };

  const columns = [
    {
      dataIndex: "name",
      title: "process Stage",
      width: "7%",
      key: "name",
      i: "",
      render: (text, record, index, i) => (
        <Input
          key={index}
          value={text}
          onChange={onInputChange("name", index, text, record, i)}
        />
      ),
    },
    {
      dataIndex: "goals",
      title: "standard",
      key: "goals",
      render: (text, record, index) => (
        <Input
          key={index}
          value={text}
          onChange={onInputChange("goals", index)}
        />
      ),
    },
    {
      dataIndex: "assists",
      title: "actual",
      key: "assists",
      render: (text, record, index) => (
        <Input
          key={index}
          value={text}
          onChange={onInputChange("assists", index)}
        />
      ),
    },
    {
      dataIndex: "name",
      title: "strength",
      width: "7%",
      key: "name",
      render: (text, record, index) => (
        <Input
          key={index}
          value={text}
          onChange={onInputChange("name", index)}
        />
      ),
    },
    {
      dataIndex: "name",
      title: "real",
      width: "7%",
      key: "name",
      render: (text, record, index) => (
        <Input
          key={index}
          value={text}
          onChange={onInputChange("name", index)}
        />
      ),
    },
    {
      dataIndex: "name",
      title: "volume",
      width: "7%",
      key: "name",
      render: (text, record, index) => (
        <Input
          key={index}
          value={text}
          onChange={onInputChange("name", index)}
        />
      ),
    },
    {
      dataIndex: "name",
      title: "ph",
      width: "7%",
      key: "name",
      render: (text, record, index) => (
        <Input
          key={index}
          value={text}
          onChange={onInputChange("name", index)}
        />
      ),
    },
    {
      dataIndex: "name",
      title: "Temp",
      width: "7%",
      key: "name",
      render: (text, record, index) => (
        <Input
          key={index}
          value={text}
          onChange={onInputChange("name", index)}
        />
      ),
    },
    {
      dataIndex: "name",
      title: "Start Time",
      width: "7%",
      key: "name",
      render: (text, record, index) => (
        <Input
          key={index}
          value={text}
          onChange={onInputChange("name", index)}
        />
      ),
    },
    {
      dataIndex: "name",
      title: "End Time",
      width: "7%",
      key: "name",
      render: (text, record, index) => (
        <Input
          key={index}
          value={text}
          onChange={onInputChange("name", index)}
        />
      ),
    },
    {
      render: (text, record, index) => {
        return (
          <Button
            type="text"
            className="dlt-action"
            key={index}
            onClick={() => handleDelete(index)}
          >
            <i className="far fa-trash-alt"></i>
          </Button>
        );
      },
    },
  ];
  const handleDelete = (index) => {
    let temp = [...tableData];
    temp.splice(index, 1);
    setTableData([...temp]);
  };
  const handlesubmit = () => {
    console.log(tableData);
  };
  const handleAddRows = () => {
    console.log(columns.length);
    const obj = {
      id: tableData.length + 1,
      name: "",
      goals: null,
      assists: null,
    };
    let temp = [...tableData];
    temp.push(obj);
    setTableData([...temp]);
  };
  const addDetails = (i) => {
    let temp = [...data];
    const obj = {
      id: temp[i].details.length + 1,
      name: "",
      goals: null,
      assists: null,
    };
    temp[i].details.push(obj);
    setdata([...temp]);
    console.log(data);
    // console.log(obj);
  };
  const callback = (k) => {
    console.log(k);
  };
  return (
    <div>
      <Collapse expandIconPosition="right" onChange={callback}>
        {data &&
          data.length > 0 &&
          data.map((section, in) => {
            return (
              <Panel key={in} header={section.section_name}>
                <Table
                  key={(record) => record.id}
                  columns={columns}
                  dataSource={section.details}
                />
              </Panel>
            );
          })}
      </Collapse>
      <Button onClick={() => handlesubmit()}>save changes</Button>
    </div>
  );
}

To perform crud operations inside each table, i would require the variable ‘in’ so that i can operate the array as required, i am not able to retrieve the information that which table the user is currently working on, and thus cannot determine the way to perform operations required like edit create and delete.
I want to know is there any way to pass the variable ‘in’ to the columns so that,i can perform operations??

Illustration: –
enter image description here

I want to add a property/key to array of objects whose value differs based on start index and stop index passed [duplicate]

I want to add a property/key to array of objects whose value differs based on start index and stop index passed.

For eg.
-I want to add the property car:blue at index 0

  • car:red from index 1 to 3
  • car:yellow at index 4 and 5.

so a function setcarColor(color,indexStart,indexEnd)

I have also added what the initial array of objects looks like and what the final one should look like


InitialObj = [{
    "id": "61f28d0679874e6644233cd3",
    "name": "abc"
  },
  {
    "id": "61f28d0679874e6644233cd3",
    "name": "efg"
  },
  {
    " id ": " 61f28d0679874e6644233cd3 ",
    " name ": "hij "
  },
  {
    " id ": " 61f28d0679874e6644233cd3 ",
    " name ": "klm",
  },
  {
    " id ": " 61f28d0679874e6644233cad ",
    " name ": "nop",
  },
  {
    " id ": " 61f28d0679874e6644233cfd ",
    " name ": "qrd",
  }
]

After using passing the values to function,The object will look like below

finalObj = [{
    " id ": " 61f28d0679874e6644233cd3 ",
    " name ": "abc",
    " car ": "blue"
  },
  {
    " id ": " 61f28d0679874e6644233cd3 ",
    " name ": "efg",
    "car": "red"

  },
  {
    "id": "61f28d0679874e6644233cd3",
    "name": "hij",
    "car": "red"

  },
  {
    "id": "61f28d0679874e6644233cd3",
    "name": "klm",
    "car": "red"
  },
  {
    "id": "61f28d0679874e6644233cad",
    "name": "nop",
    "car": "yellow"

  },
  {
    "id": "61f28d0679874e6644233cfd",
    "name": "qrd",
    "car": "yellow"
  }
]

Dynamic welcome of navbar in reactJs

I have a doubt regarding dynamically rendering the logged in user’s name in the NavBar in react.

So my app is structured in the following way

<App>
<Header/>
<Router>
....
<Router/>
<Footer/>
<App/>

Now inside the header component, I need to display “Welcome <user>” whenever the user is logged in. Here are some solutions that I thought of,but Not sure if I’m missing out on anything.

  1. To send it as a prop to the header. But it can only be dynamic if I do a setState in the App component and re render the entire app component (Which I want to avoid)
  2. To store it in redux, so header can dynamically get the updated. But since I am using JWT, and the user needs to stay logged in, If the user refreshes the page, store content will be wiped out.
  3. I can store the username in localstorage as well, but the entire app would still need to be re rendered in order to display the change

-) I think it can be accomplished in Angular by BehaviorSubject, but in this scenario, I’m clueless.

Is there any solution or method that I am missing?
Thanks in advance

Why cookie with isHTTPOnly is not set?

Do you have any idea why cookie is not set in client? It is sent from backend:

func loginEmail(_ req: Request) throws -> Response
{
    let params = try req.content.decode(LoginEmailIn.self)
    let response = Response(status: .ok)
    if params.email == "test" && params.password == "test" {
        //req.session.data["userId"] = "abcd"
        
        let cookie = HTTPCookies.Value(string: "abcdef", expires: Date().addingTimeInterval(10000), maxAge: 300000, isSecure: false, isHTTPOnly: true, sameSite: HTTPCookies.SameSitePolicy.none)
        response.cookies["userId2"] = cookie
    }
    //return HTTPStatus.ok
    return response
}

it is visible in browser in Network tab

set-cookie: userId2=abcdef; Expires=Mon, 31 Jan 2022 07:24:55 GMT; Max-Age=300000; Path=/; Secure; HttpOnly; SameSite=None

but not on Application
enter image description here

POST is sent to loginEmail.

How to get the size of data in a Node JS Stream

So I am using this npm Library that returns SoundCloud music as a Stream. But after a while searching for an answer, I couldn’t get an answer. I searched and discovered that it is impossible to get the size of the data in a stream. But, is there a way for me to get the size of the data in that stream because I plan on using the size, to implement download progress in my app. Thanks a lot in advance.

Trying to drag and drop onto an SVG canvas with accurate coordinates

I am trying to implement drag and drop an image element onto an SVG canvas but the elements are not in the same div. I have tried to use clientX and clientY properties but they are out by about 20 pixels when I come to drop the element. I think the problem is that the SVG coordinates work from the top of the root SVG element but drag and drop coordinates are from the visible view port. When I try to release the rock image on the canvas it just seems to go to any random place on it and sometimes off the canvas completely.

Screenshot of my attempt

I have uploaded all my code to https://github.com/kiwiheretic/gravity

Any idea what javascript mouse event attributes and element attributes to work out my SVG coordinates for drag and drop?