Output dates between selected days via indexOf

I make a datepicker on vue3, When choosing two dates, I need the days between the selected dates to be hover. I use the “indexOf” method, but the desired result is not obtained

<div
            v-for="date in daysInMonth(currentYear, currentMonthInNumber, firstDay, lastDay)"
            :key="date"
            ref="date"
            class="day"
            :class="{ active: date === firstDay || date === lastDay, between: between.indexOf(date)}"
            @click="choosingDates(date)" > {{ date }} </div>
<script>
      firstDay: false,
      between: [],
      lastDay: false,
      firstDaySelected: false,
    };
  },
  methods: {
    choosingDates(date) {
      if (this.firstDay === false) {
        this.firstDay = date;
      } else if (this.lastDay === false) {
        this.lastDay = date;;
      }
    },

With this code, “between” hover all days of the month (css styles are written)
:class=”{ between: between.indexOf(date)} ”
what i do wrong

Why does my variable return a different value than what the getter evaluates? [closed]

I have the following code:

async method() {
        const values: RequestForHelp[] = await databaseHelper.getUnacceptedAndUnsucceededRequests();
        for (const request of values) {
            request.userHelpMeLatitude = 19;
            request._userHelpMeLatitude = 20;
            console.log(request.userHelpMeLatitude);
            console.log(request._userHelpMeLatitude);
        }
    }

Why does the first console.log return 19, and the second one 20?

class RequestForHelp{

public _userHelpMeLatitude: number |string; 

public get userHelpMeLatitude(): string | number {
    return this._userHelpMeLatitude;
    }

public set userHelpMeLatitude(value: number | string) {
    this._userHelpMeLatitude = value;
}

}
export {RequestForHelp};

Thank you in advance

JavaScript prototypical inheritance to object methods [duplicate]

one quick question.

I know i can make a class and do it with “this”, keyword, but can i somehow do it alternatively via prototypical inheritance?

Example:

const obj1 = {
    name: "Admin",
    log: () => console.log(obj1.name),
};

I make a object with a name and a method that console.logs obj1’s name

const obj2 = {
    name: "Moderator",
};

obj2.__proto__ = obj1;

So i make another object that only has a name, without log method, and i do prototypical inheritance so obj2 now has access to that method even if it’s not created with it.

obj2.log();

// output: "Admin"

How can i bind log method to the object that calls it, so if i use it as obj2 through prototypical inheritance, it will log obj2’s name “Moderator”

How to get the choice(value) out of datalist in javascript?

I developing a probability calculator and I can’t manage to get the ‘value’ out of the datalist. I’m very new to javascript so maybe it’s very easy but I don’t know how to do it yet.
Here’s my javascript code:

//test
let test = document.getElementById("name");
test.addEventListener("input", () => console.log(test.value));


// variables
let q = document.getElementById("submit");
let q1 = document.getElementById("q1");


q.addEventListener('click', () => console.log("works"));
q.addEventListener('click', probability_calculation()));

function probability_calculation()
{
    if(q1.value === 'Rap')
    {
        alert("works");
        console.log("works well");
    }
    else if(q1.value === 'Alter')
    {
        console.log('33%');
    }
    else if(q1.value === 'Pop')
    {
        console.log('97%');
    }
}

and here’s the html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="keywords" content="Probability">
    <title>Probability Calculator</title>
</head>

<body>
    <h1 class="header">Probability Calculator</h1>    
    <div>
        <input type="text" placeholder="Enter your name" id="name">
        <input list="q1" placeholder="What is your favourite type of music?">
    </div>
    <panel class="center-q">
        <datalist id="q1">
            <option>Rap</option>
            <option>Alter</option>
            <option>Pop</option>
        </datalist>
    </panel>
    <input type="submit" id="submit">
    
    <script src="index.js"></script>
    <link rel=stylesheet href="index.css">
</body>
</html>

I tried using object.value but it does not seem to work. Do you have any ideas?

How to pass data between pages in react when using useparams()?

App.jsx

import './App.css'
import React, {useState} from 'react';
import { Link, Routes, Route } from 'react-router-dom';
import Calendar from "./components/calendar/calendar.jsx";
import ToDo from "./components/todolist/todolist.jsx";
import { useParams } from 'react-router-dom';

const App = () => {

    return (
        <div>
            <Routes>
                <Route path='/' element={<Calendar  />} />
                <Route path='/todo/:id' element={<ToDo />} />
            </Routes>
        </div>
    )
}

export default App;

calendar.jsx

import './calendar.css'
import {Link} from 'react-router-dom'
import React from "react";

const Calendar = () => {

    return (
        <div className="month">
            <h1> February 2023 </h1>
            <div className="names">
                <div className="weekNames">Monday</div>
                <div className="weekNames">Tuesday</div>
                <div className="weekNames">Wednesday</div>
                <div className="weekNames">Thursday</div>
                <div className="weekNames">Friday</div>
                <div className="weekNames">Saturday</div>
                <div className="weekNames">Sunday</div>
            </div>
            <div className="week">
                <div className="day">1 <Link to='/todo/1'> To-Do:  </Link> </div>
                <div className="day">2 <Link to='/todo/2'> To-Do:  </Link> </div>
                <div className="day">3 <Link to='/todo/3'> To-Do: </Link> </div>
                <div className="day">4 <Link to='/todo/4'> To-Do: </Link> </div>
                <div className="day">5 <Link to='/todo/5'> To-Do: </Link> </div>
                <div className="day">6 <Link to='/todo/6'> To-Do: </Link> </div>
                <div className="day">7 <Link to='/todo/7'> To-Do: </Link> </div>
                <div className="day">8 <Link to='/todo/8'> To-Do: </Link></div>
                <div className="day">9 <Link to='/todo/9'> To-Do: </Link> </div>
                <div className="day">10 <Link to='/todo/10'> To-Do: </Link> </div>
                <div className="day">11 <Link to='/todo/11'> To-Do: </Link> </div>
                <div className="day">12 <Link to='/todo/12'> To-Do: </Link> </div>
                <div className="day">13 <Link to='/todo/13'> To-Do: </Link> </div>
                <div className="day">14 <Link to='/todo/14'> To-Do: </Link> </div>
                <div className="day">15 <Link to='/todo/15'> To-Do: </Link> </div>
                <div className="day">16 <Link to='/todo/16'> To-Do: </Link> </div>
                <div className="day">17 <Link to='/todo/17'> To-Do: </Link> </div>
                <div className="day">18 <Link to='/todo/18'> To-Do: </Link> </div>
                <div className="day">19 <Link to='/todo/19'> To-Do: </Link> </div>
                <div className="day">20 <Link to='/todo/20'> To-Do: </Link> </div>
                <div className="day">21 <Link to='/todo/21'> To-Do: </Link> </div>
                <div className="day">22 <Link to='/todo/22'> To-Do: </Link> </div>
                <div className="day">23 <Link to='/todo/23'> To-Do: </Link> </div>
                <div className="day">24 <Link to='/todo/24'> To-Do: </Link> </div>
                <div className="day">25 <Link to='/todo/25'> To-Do: </Link> </div>
                <div className="day">26 <Link to='/todo/26'> To-Do: </Link> </div>
                <div className="day">27 <Link to='/todo/27'> To-Do: </Link> </div>
                <div className="day">28 <Link to='/todo/28'> To-Do: </Link> </div>
            </div>
        </div>
    );
}

export default Calendar

todolist.jsx

import './todolist.css'
import React from "react";
import { NavLink } from "react-router-dom";
import { useParams } from 'react-router-dom';

const ToDo = () => {
  const {id} = useParams()
  const [todos, setTodos] = React.useState(() => JSON.parse(localStorage.getItem(`todos-${id}`)) || []);
  const [todo, setTodo] = React.useState("");
  const [todoEditing, setTodoEditing] = React.useState(null);
  const [editingText, setEditingText] = React.useState("");

  React.useEffect(() => {
    const json = JSON.stringify(todos);
    localStorage.setItem(`todos-${id}`, json);
  }, [todos, id]);

  function handleSubmit(e) {
    e.preventDefault();
    const newTodo = {
      id: new Date().getTime(),
      text: todo,
      completed: false,
    };
    setTodos([...todos].concat(newTodo));
    setTodo("");
  }

  function deleteTodo(id) {
    let updatedTodos = [...todos].filter((todo) => todo.id !== id);
    setTodos(updatedTodos);
  }

  function toggleComplete(id) {
    let updatedTodos = [...todos].map((todo) => {
      if (todo.id === id) {
        todo.completed = !todo.completed;
      }
      return todo;
    });
    setTodos(updatedTodos);
  }

  function submitEdits(id) {
    const updatedTodos = [...todos].map((todo) => {
      if (todo.id === id) {
        todo.text = editingText;
      }
      return todo;
    });
    setTodos(updatedTodos);
    setTodoEditing(null);
  }


  return (
    <div>
      <div align='right'>
        <NavLink to='/' style={{textDecoration: 'none', color: 'black'}}><button className='btn'> Calendar View </button></NavLink>
      </div>
      <div id="todo-list">
        <h1>To-Do For Today</h1>
        <h2> Total Tasks: {todos.length} </h2>
        <form onSubmit={handleSubmit}>
          <input
            type="text"
            onChange={(e) => setTodo(e.target.value)}
            value={todo}
          />
          <button className="btn">Add To-Do</button>
        </form>
        {todos.map((todo) => (
          <div key={todo.id} className="todo">
            <div className="todo-text">
              <input
                type="checkbox"
                id="completed"
                checked={todo.completed}
                onChange={() => toggleComplete(todo.id)}
              />
              {todo.id === todoEditing ? (
                <input
                  type="text"
                  onChange={(e) => setEditingText(e.target.value)}
                />
              ) : (
                <div>{todo.text}</div>
              )}
            </div>
            <div className="todo-actions">
              {todo.id === todoEditing ? (
                <button className='btnXS' onClick={() => submitEdits(todo.id)}>Submit</button>
              ) : (
                <button className='btnXS' onClick={() => setTodoEditing(todo.id)}>Edit</button>
              )}

              <button className='btnXS' onClick={() => deleteTodo(todo.id)}>Delete</button>

            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default ToDo;

I am trying to built a calendar web app with daily to-do lists. So when clicking on the link on any day, the user should be able to add and edit what to do for that day. But I would also like to show the total number of todos added for each day in the calendar page. E.g. 1 To-Do: “show total numbers of to-dos for this day”

I tried calling {todos.length} on the calendar page, but it always shows 0.

Fetch always returns 200 even when server returns 400 or some error. How to get correct result?

I have below function in frontend, I have to make some api call here in this function. When i checked the called function via command prompt, the server api call returns 400. but the function in frontend fetch always returning 200 instead of error.

Please guide to how to correct response which is thrown from server call?
Here is the frontend function.

function  processFile()
        {
        var fileToLoad = document.getElementById("fileToLoad").files[0];
        var url;
         
            var fileReader = new FileReader();
            fileReader.onload = function(fileLoadedEvent) 
            {
                    var rows =fileLoadedEvent.target.result.split("n");
                    for (var i = 0; i < rows.length-1; i++) 
                    {
                        var cells = rows[i].split(",");
                        //alert(cells);
                        console.log("AgentteamID="+cells[0]+" SkilltargetID="+cells[1]+" flag="+cells[2]);
                        url= "/updateAgentTeam?agentTeamID="+cells[0]+"&skillTargetID="+cells[1]+"&flag="+cells[2],
                        //alert(url);
                        console.log("URL="+url);
                        const response = fetch(url, {
                            method: 'GET',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                                                
                    })                   .then(response => 
                        response.json().then(data => ({
                            data: "success",
                            status: response.status
                    })
                    ).then(res => {
                        var statusCode = JSON.stringify(res.status);
                        //$('#Success_comment').html(JSON.stringify(res)+"---"+url;);
                        //alert(url);
                        document.getElementById("Success_comment").value += JSON.stringify(res)+"---"+url;
                        console.log("final result "+JSON.stringify(res)+"---"+url);
                            
                        }))                     
                    
              }
            }
            fileReader.readAsText(fileToLoad, "UTF-8");
        }

Here is the Server side code. For now we are using only Flag A block

app.get("/updateAgentTeam",(req,res) => {
    var skillTargetID = req.query.skillTargetID;
    console.log("req.query.skillTargetID ="+req.query.skillTargetID);
    var agentTeamID = req.query.agentTeamID;
    var flag = req.query.flag;
    var finalurl="http://198.18.133.11/unifiedconfig/config/agentteam/"+agentTeamID;
    var xml;
    //console.log("finalurl ="+finalurl);
    axios({
        url: finalurl,
        method: "get",
        auth: {
        username: "[email protected]",
        password: "C1sco12345"
        }, 
    })
    .then(async (response) => {
        xml=response.data;
        //console.log("after calling xml is "+JSON.stringify(xml));
        res.send(response.data);  
                   
        if(flag=== 'D')
        {   
            agentremovedXML=removeAgentFromXML(xml,skillTargetID);
            //newxml=removeAgentFromXML(xml);
            //console.log("Final Agent remove XML "+JSON.stringify(agentremovedXML));
            postAgentToTeam(agentTeamID,agentremovedXML);
            //setSuccessJSON();
        }
        else if (flag==='A')
        {
            AgentXML= await generateAgentXML(skillTargetID);
            console.log("Returned agent xml is "+JSON.stringify(AgentXML));
            console.log("xml where agent to be add "+JSON.stringify(xml));
            if(JSON.stringify(xml.agentCount)==0){
                AgentXML = {"agent":[AgentXML]};

                xml.agents = [ AgentXML ];
                console.log("xml with zero agents "+JSON.stringify(xml));
            }
            else{
                xml.agents[0].agent.push(AgentXML);
                console.log("Compare "+JSON.stringify(xml));
            }
            console.log("xml send to postAgentToTeam is "+xml);
            postAgentToTeam(agentTeamID,xml);
            //postAgentToTeam(agentTeamID,agentXML);
        }       
    })
    .catch((err) => {
        res.send(err.response.status);
        console.log(err);
        //setErrorJSON()
    });  
});

async function postAgentToTeam(agentTeamID,xml){    
    var teamurl="http://198.18.133.11/unifiedconfig/config/agentteam/"+agentTeamID;
    //console.log("final XML is "+JSON.stringify(xml));
    xml.agents = xml.agents[0].agent.map(agent => ({agent: agent}));
    var updatedJSONwithAgentTags = JSON.stringify(xml,null," ");
    //console.log("newwwwwwwwwwwwwwwwwwwwww "+ updatedJSONwithAgentTags);
    //return;
    js2xml=json2xml(JSON.parse(JSON.stringify(xml)));     
    json2="<agentTeam>"+js2xml+"</agentTeam>";
    //console.log("newwww converted XML "+json2);
    response = await axios({
        url: teamurl,
        method: "put",
        auth: {
        username: "[email protected]",
        password: "C1sco12345"
        },
        data:json2,
        headers:{'Content-Type': 'application/xml; charset=utf-8'}
    })
    .then(response => {
        console.log("hellooo "+response.status);
    })  
    .catch((err) => {
        console.log(err.response.data.apiError);
        console.log("error res is "+err.response.status);
    }); 
}

Ggiraph Onclick to open a file in a relative folder path when accessing plot rendered into an HTML widget

I am trying to use the ggiraph package for one of my plotting requirements.
I intend to use the Onclick functionality of the geom_point_interactive function to allow me to open a local image file (with relative folder path to the final rendered html widget) when a point on a graph is clicked while also having the hover label(tooltip) display when the cursor is above the point.
I see a few examples of linking the onclick to a webpage, but nothing explaining to local file access. The windows default security also prevents in most cases local file access links in html pages when accessed on a browser. How do we overcome these challenges?
Can anyone pl share an example of how to achieve the same for opening an image file on local relative folder path upon “Onclick”? [JavaScript]

Thanks

i tried passing window.open (“~/folderpathname/filename.png”)
This doesn’t work as intended.

I have a problem SQLITE_RANGE: column index out of range

That’s my code.

const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('./db/mob1.db')
let dostup = "SELECT dostup FROM users WHERE idds = 506043416812191764";


db.get(dostup, [dostup], (err, row) => {
    if (err) {
        return console.error(err.message);
    }
    return row
        ? console.log(row.id, row.name)
        : console.log(`No text found with the id ${dostup}`);

});

// close the database connection
db.close();

I tried to put everything in a variable and sign ${iddsmember}, but writes that SQLITE_ERROR: unrecognized token: “$”

ssh2-sftp-client throwing an error when client function is passed as parameter

I’m using the ssh2-sftp-client library with Typescript to connect to an sftp server – the connection works, however when I create a wrapper function to include the ‘connect’ and ‘end’ functions around the main function call I get an error from the main function being called.

The wrapper function:

private async session(callback: Function, ...args): Promise<any> {
    let output;

    await this.sftpClient.connect(credentials);

    try {
      output = await callback(...args);
    } catch (err) {
      throw err;
    } finally {
      await this.sftpClient.end();
    }

    return output;
  }

The calling function:

async getFilesList(path: string): Promise<object[]> {
      return await this.session(this.sftpClient.list, path);
  }

The error received:
list: Error removing temp listeners: Cannot read properties of null (reading 'removeListener')

If I call the function directly (replace callback(...args) with this.sftpClient.list(...args)) then it works fine.

If I use this:
output = await callback.apply(this, args)
then I get a slightly different error:
list: Error removing temp listeners: Cannot read properties of undefined (reading 'end')

Trying to return a different color div after selecting option in form submit using React and Typescript

I am working on a to do list using React and Typescript. I am trying to return a different colored div when selecting a priority in the option select dropdown (prioritySelect). I have tucked in a function within the ToDoItem JSX Element. What I want to happen is for the prioritySelect component to change the background color of the div it is in “to-do-item” to signify importance.

I tried to add handleOptionsChange function and call it within the div return at the bottom but I keep running into errors when trying to add handleOptionsChange, I am not sure why.

//TODOITEM TO RETURN TO DO COMPONENT

`function ToDoItem(props: { toDo: ToDo; onDeleteToDo: any; prioritySelect: any;}) {`

///TRYING TO CREATE FUNCTION EXPRESSION THAT CALLS EVENT SET STATE FOR PRIORITY BELOW

`handleOptionsChange:any; setState:any;}) {
  handleOptionsChange = (event: any) => {
    props.setState({
      option: event.target.value
    });
  }`



`return (
    <div className="to-do-item" id="to-do-item">
      <div className="checkbox-title-container">
        <div className="check-title-div">
        {Checkbox()}
        <h2 className="to-do-title">{props.toDo.title}</h2>
        </div>
        <div id="delete-div">`

//PRIORITY OPTION SELECT BELOW

    `<select name="Priority" className="select-field" value={props.prioritySelect.option} onChange={props.handleOptionsChange}>
          <option className="important" value='1'>Important</option>
          <option selected value='2'>Normal</option>
          </select>
      <button id="delete" onClick={props.onDeleteToDo}>
        Delete
      </button>
    </div>
  </div>
  <div className="description-box">
    <span className="description">{props.toDo.description}</span>
  </div>
  <br />
  <span className="to-do-date">
    {/* {props.toDo.duedate.toLocaleDateString()} */}
  </span>
</div>

);
}`

I am trying to call handleOptionsChange when returning a JSX component below, I have taken out the rest of the components within the to-do-item div for the sake of readability

  `<div className="to-do-item" id="to-do-item">
  {prioritySelect={handleOptionsChange}} </div>
  <div>`

Value is not updated immediately in one place however it is updated in the other in typescript

I have a page that is split into left pane and right pane. The left pane has an option with label “Firmware” which when clicked the right pane displays the corresponding page. The left pane has also a button which when clicked takes us through a series of steps in a wizard. once the wizard is closed the value near the label is updated to the current version but in the right pane there is a conditional rendering based on the same version variable but it is not updated at the first instance. I have to move to a different page and come back to see the changes. I cannot use composition-api since I dont have permission to install that. Is there a way to solve this and also why it is happening. Below is some code for better understanding of the problem.

right pane -vue file

<q-item-label header v-if="!room.uxOneVersion">
  {{ $t('pages+.projects.firmwares.noVersion') }}
  <span class="lt-md">
    <br />
  </span>
  {{ $t('pages.projects.firmwares.connectThermostat') }}
</q-item-label>
<q-item-label
  class="q-mb-md"
  header
  v-if="room.uxOneVersion && room.uxOneVersion >= versionCheck"
>
  {{ $t('pages.projects.firmwares.noUpgradeAvailable') }}
  <span class="lt-md">
    <br />
  </span>
  {{ $t('pages.projects.firmwares.latestCheck', { date: date, hour: hour }) }}
</q-item-label>
<q-item-label
  class="q-mb-md"
  header
  v-if="room.uxOneVersion && room.uxOneVersion < versionCheck && versionCheck"
>
  {{ $t('pages.projects.firmwares.upgradeAvailable') }}
</q-item-label>

Typescript file for the right pane

async searchUpdate() {
    localStorage.setItem('date', new Date().toLocaleDateString());
    localStorage.setItem(
      'hour',
      new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    );
    try {
      this.onSearchFirmware = true;
      if (await Helpers.isHostDeviceOnline()) {
        const firmwareUpdaterResponse = await this.isFirmwareUpToDate(this.firmwareUpdater);
        if (
          firmwareUpdaterResponse &&
          !firmwareUpdaterResponse?.isUpToDate &&
          this.room.uxOneVersion < firmwareUpdaterResponse?.version &&
          this.versionCheck != firmwareUpdaterResponse?.version
        ) {
          localStorage.setItem('version', firmwareUpdaterResponse.version);
          this.versionCheck = localStorage.getItem('version');
          this.notifyAvailabilityOfNewVersionFirmware(firmwareUpdaterResponse);
          this.date = localStorage.getItem('date');
          this.hour = localStorage.getItem('hour');
        } else {
          this.notifyNoVersionFirmwareAvailable();
          this.date = localStorage.getItem('date');
          this.hour = localStorage.getItem('hour');
        }
      } else {
        Notifier.showError(this.$t('general.internetNotConnected').toString());
      }
    } catch (error) {
      const errorMessage = this.$t('pages.projects.firmwares.isUpToDateError', {
        error_message: (error as FirmwareUpdaterError).message,
      }).toString();
      Notifier.showError(errorMessage);
    } finally {
      this.onSearchFirmware = false;
    }
  }

left pane- vue

<q-item-section side>
  <div>
    <q-chip style="background: transparent"></q-chip>
    <q-chip data-cy="firmware-Version" v-if="room.uxOneVersion != ''"
      >{{ $t('general.currentVersionFirmware') }} {{ room.uxOneVersion }}</q-chip
    >
    <q-icon size="xs" color="grey" name="chevron_right" />
  </div>
</q-item-section>

Typesciprt for right pane

this.handleConnectionDialogVisibility(false);
  await this.getVersionUxOne();
  await this.openIdentifyDialog();
}
private async getVersionUxOne() {
  this.firmwareVersionToDisplay = '';
  const controllerUpdater = ControllerFirmwareUpdaterFactory.create(
    this.roomControllerModuleStore.currentController.controllerType,
    this.deviceModuleStore.currentNetworkAddress,
    this.deviceModuleStore.currentPassword
  );
  const currentControllerVersion = await controllerUpdater.getVersion(); //0.2.9
  const room: RoomEntity = this.roomModuleStore.currentRoom;
  room.uxOneVersion = `${currentControllerVersion}`; //0.2.9
  this.firmwareVersionToDisplay = `v ${currentControllerVersion}`; //v 0.2.9
  await this.roomModuleStore.updateRoom(room);
  await this.roomModuleStore.setCurrentRoom(this.roomModuleStore.currentRoom.Id);
}

Merge array of an object based on a common field

I have an object that looks like as follows:

[
    {
        "Net_Amount": 499,
        "Date": "2022-01-09T18:30:00.000Z",
        "Scheme_Name": "CUSTOMERWINBACKJCA01",
        "Month": "Jan"
    },
    {
        "Net_Amount": 902,
        "Date": "2022-01-09T18:30:00.000Z",
        "Scheme_Name": "CUSTOMERWINBACKJCA02",
        "Month": "Jan"
    },
    {
        "Net_Amount": 1860,
        "Date": "2022-10-01T18:30:00.000Z",
        "Scheme_Name": "CUSTOMERCONNECTJCA",
        "Month": "Oct"
    },
    {
        "Net_Amount": 1889,
        "Date": "2022-11-01T18:30:00.000Z",
        "Scheme_Name": "CUSTOMERCONNECTJCA",
        "Month": "Nov"
    }
]

Now, if you will look carefully, I have a common field Month in the objects and I want merge the objects based on this common field only. How I want my object to be formatted is as :

[
    {
        "Month": "Jan",
        "varData":  [{
            "Net_Amount": 499,
            "Date": "2022-01-09T18:30:00.000Z",
            "Scheme_Name": "CUSTOMERWINBACKJCA01"
        },
        {
            "Net_Amount": 902,
            "Date": "2022-01-09T18:30:00.000Z",
            "Scheme_Name": "CUSTOMERWINBACKJCA02"
        }]
    },
    {
        "Month": "Oct",
        "varData":  [{
            "Net_Amount": 1860,
            "Date": "2022-10-01T18:30:00.000Z",
            "Scheme_Name": "CUSTOMERCONNECTJCA"
        }]
    },
    {
        "Month": "Nov",
        "varData":  [{
            "Net_Amount": 1889,
            "Date": "2022-11-01T18:30:00.000Z",
            "Scheme_Name": "CUSTOMERCONNECTJCA"
        }]
    }
]

I can do it by iterating over the array and checking if month is same, then pushing the other key and its value of object in the varData but I want to know if there is any shortcut or inbuilt function which I can use to achieve my purpose.

Common search algorithms?

Let us say we have the following JavaScript array:

const books = [
  {
    title: "The Great Gatsby",
    description: "A novel about the decadence of the Roaring Twenties and the American Dream"
  },
  {
    title: "To Kill a Mockingbird",
    description: "A classic novel about racial injustice and growing up in the South"
  },
  {
    title: "1984",
    description: "A dystopian novel about a totalitarian government that controls every aspect of its citizens' lives"
  }
];

Now I want to filter the books according to the user query. The code then looks like this:

function validateQuery(string, query) {

}

books.filter(book => validateQuery(book.title, "Gatsby great"));

Let us say we are looking for the book The Great Gatsby

All of these queries should return true when being passed to the validateQuery function:

  • Gatsby great
  • The great
  • Gre th
    • The grea gatsby *

Which means that:

  • the query is case insensitive
  • multiple whitespaces at the start and end of the query and inbetween the words are not a problem
  • the order of the words does not matter
  • the words do not have to be right next to each other, so it is like multiple words

What could the body of the validateQuery function look like?

I thought of using RegExp to solve the problem, but maybe there is an even simpler solution which does not need RegEx. Maybe there is also a common algorithm out there to solve this problem, even though I did not find anything on Google.