Best way to filter an array of objects by Index in JavaScript

I have an array of objects like this

export const productArray = [

  { 
    imgUrl: images.beautifulinwhite,
    productName: "White Flowers",
    oldPrice: "$45.99",
    newPrice: "$35.99",
  },
  {
    imgUrl: images.blueandpinkjeans,
    productName: "Blue and Pink Jeans",
    oldPrice: "$57.99",
    newPrice: "$40.99",
  },
  {
    imgUrl: images.girlinyellow,
    productName: "Yellow Tshirt",
    oldPrice: "$53.99",
    newPrice: "$37.99",
  },
  {
    imgUrl: images.ladyinblack,
    productName: "Black Hoodie",
    oldPrice: "$40.99",
    newPrice: "$33.99",
  },
]

How do I filter this array to only get the first two objects? I don’t want to filter them by their attributes. I want to filter using their indexes .

React Native Button taking CSS of Previous Button

I am setting Buttons stack on the basis of a variable whether channel is joined or not.
One button is “Join Channel” which a plain text button
Second button is “End Call” button which is a Circular button with an icon.
Both have different CSS.
When I click on “Join Channel”, channel is joined and my stack is changed.
Then I click on “End call” button, but CSS of this button does not remove and applied to “Join Channel” Button. Background color is not removed.

Rendering Code:

{this.state.isJoined ? this._callButtonsView() : this._joinButtonView()}
_joinButtonView = () => {
    return (
      <View style={styles.buttonsContainer}>
        <Button
          title="Join Channel"
          buttonStyle={styles.joinButton}
          titleStyle={{color: 'green', fontSize: 20}}
          onPress={() => this._joinChannel()}
        />
      </View>
    );
  };

  _callButtonsView = () => {
    return (
      <View style={styles.buttonsContainer}>
        <Button
          icon={{
            name: 'call-end',
            color: '#ff0000',
            size: 25,
          }}
          buttonStyle={styles.actionButton}
          onPress={() => this._leaveChannel()}
        />
      </View>
    );
  };

CSS:

actionButton: {
    backgroundColor: 'blue',
    padding: 0,
    height: 50,
    width: 50,
    marginRight: 25,
    marginTop: 5,
    marginBottom: 5,
    borderRadius: 25,
  },
  joinButton: {
    backgroundColor: 'clear',
  },

Video:

enter image description here

image is coming over input element in react js

when I launch the page, the browser extension icon(marked in red) is static and it is at the beginning.

enter image description here

when I type it keeps moving and covers the last typed text.

enter image description here

is there any css property through which I can prevent it coming on my component. I alredy tried

  input{
     background:none !important
     background-image:none !important
  }

but its not working.

I am using react and .scss file for css. this issue is not in other elements or components.

Can’t find the way to calculate and output it

I’m trying to get the percentage from the “timeSpend” and “breakTime” and store in fSubject,sSubject, tSubject and store it in dataset: date[],
so that it can output it but it just gives the value of “timeSpend” and “breakTime” not fSubject,sSubject, tSubject enter image description here

 let timeSpend = document.querySelector("#time_spend").value;
let breakTime = document.querySelector("#break_time").value;
let fSubject = document.querySelector("#first_subjects").value;
let sSubject = document.querySelector("#second_subjects").value;
let tSubject = document.querySelector("#third_subjects").value;

let fSubjectV = (50/100) * (timeSpend + breakTime); 
let sSubjectV = (25/100)* (timeSpend + breakTime);
let tSubjectV = (25/100)* (timeSpend + breakTime);

let myChart = document.getElementById("myChart").getContext("2d");

document.querySelector("button").addEventListener("click", () => {
    let pieChart = new Chart(myChart, {
        type: "pie",
        data: {
            labels: [
                "Time spend",
                "Break Time",
                "First Subject",
                "Second Subject",
                "Third Subject",
            ],
            datasets: [
                {
                    label: "Plan",
                    data: [
                        timeSpend.value,
                        breakTime.value,
                        fSubjectV.value,
                        sSubjectV.value,
                        tSubjectV.value,
                    ],
                },
            ],
        },
        options: {},
    });
});

PHP nl2br for text content but make it exclude on javascript content

I need to use nl2br function on page content coming from DB. But <br /> tag added to into javascript content too.

<script type="text/javascript"><br />
let test = "test";<br />
let menu = "menu";<br />
</script>

Firstly for make add br to all content and than remove br from javascript content, I did try this:

<?php
//content coming from db
$content = nl2br($content);
$content = preg_replace("/<scriptb[^>]*>([sS]*?)</scriptb[^>]*>/m", str_replace("<br />", "", nl2br($content)), $content);
echo $content;
?>

Result: br not added into javascript but javascript and text content did come twice (br didn’t worked on first text content but worked on second text content)

How can I exclude br in javascript code?

Cannot show image by img.src

I have no idea why setting img.src with import is fine but when I pass the path to it doesn’t work.

import mahjong_tiles from '../assets/mahjong_tiles/1man.png'

const displayTileArr = () => {
    var img = document.createElement('img');
    img.src = mahjong_tiles ; //OK
    img.src = '../assets/mahjong_tiles/1man.png';  //NOT OK
    document.getElementById('display-hand').appendChild(img);   
}

How do I hide all objects in a “source” (geoJson) in MapBox GL JS based on whether their description matches my string?

I’ve long tried to implement this feature for my map system, because I have lots of markers loaded in and it’s very useful to be able to enter a string such as “abc” into an input field to “filter out” (visually hide) all the ones that don’t contain that string inside of their description/title.

A few weeks ago, I found this example: https://docs.mapbox.com/mapbox-gl-js/example/filter-markers/

Unfortunately, they do it in a completely silly manner which doesn’t apply to my situation, so I was only able to grab the basic input part from their example. Then I got stuck. I tried countless things and after many hours of work, I at least have finally managed to be able to loop through my loaded-in geoJson “sources” (containing all the markers). So, I have this:

filterInput.addEventListener('keyup', (e) =>
{
    const value = e.target.value.trim().toLowerCase();

    let sources = Object.entries(map.getStyle().sources);

    for (const source of sources)
    {
        if (source[1].type == 'geojson')
        {
            console.log(source[0]); // The name of the source, for example "my nostalgic visited places".
            
            // Here, I'm trying to loop through all the inidividual markers of this geoJson "source" and, based on "value" and its title/description, either visually hide or display it. This is the part I just cannot figure out.
        }
    }
});

I obviously need to loop through the markers inside each geoJson inside my sources for loop, but how? I don’t know:

  1. How to actually loop through those in the first place. I can’t find any in the source object.
  2. How to tell MapBox GL JS to hide/show them individually. The example that they have just bulk hide/show entire layers/sources, which is irrelevant.

If it helps, console.log(source[1]); causes this kind of output:

{type: 'geojson', data: 'http://127.0.0.1/mymap/geoJSON/my nostalgic visited places.geojson'}
data: "http://127.0.0.1/mymap/geoJSON/my nostalgic visited places.geojson"
type: "geojson"
[[Prototype]]: Object

Disappointingly, the [[Prototype]]: Object does not seem to contain any neat array of markers, as I first assumed would be the case. I don’t know what to make of it.

JS button must be clicked twice on first use – why?

I have two buttons on a web page (Previous and Next) and both have a function associated with their click event:

//Add click events for the next and previous buttons
document.getElementById("previous").addEventListener("click", selectSection);
document.getElementById("next").addEventListener("click", selectSection);

The code for selectSection is:

Blocking and non blocking code in parallel

I need to be able to run some code that is going to be blocking and some other code that will then, when blocked, start some other actions.

The usecase is the follows:

I have a file called index.ts running an express and socket server

I have a testfile called test.spec.ts that needs to be able to start the express server and then initiate some commands for running tests either via HTTP request or socket message(I would prefer HTTP)

The only way I found to keep the webserver alive is instanciating it with

import { spawnSync } from 'child_process';

spawnSync('ts-node', ['path/to/index.ts"], { cwd: "path/to/workdir"});

which will block until the child process is killed( could be up to 30min later).

Is there a way to split into two processes, one that gets blocked when starting it and one continuing to work that exposes some functions for interactions with the test file?

My target would look like this:

// index.ts

import * as express from "express";
const app = express();

const port = 3000;

app.get('/', (req, res) => {
    res.send('Hello World!');
});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});
// test.spec.ts

import { spawnSync } from 'child_process';

describe("Test",()=>{

  it("Test", async ()=>{

    // create somehow a child process that should block
    const childProcess = ...
    childProcess.do(spawnSync('ts-node', ['path/to/index.ts'], {cwd: 'path/to/workdir'}) //should block now

    // the following code should run in parallel
    await new Promise(r => setTimeout(r, 5000)); //wait some time until the webserver is ready

    fetch('http://localhost:3000').then((ret)=>{
      expect(ret,'to be Hello World').to.contain('Hello World!");
    })
    ... // more tests
  });
});

How to replace a substring between two indexes ignoring HTML tag in JavaScript

I want to replace a substring in a text between two indexes. But I want to ignore any HTML tag when counting the index.

For example

If the text is the best kitchen knife I want to replace the substring from index 4 to 8 with ‘nice’ so the output should be the nice kitchen knife

But if the text is in HTML tag like
<li>the best kitchen knife</li>
or
<li>the <span>best</span> kitchen knife</li> and given indexes are 4 and 8, it should count from ‘the’ not from <li>. So the expected output should be <li>the <span>nice</span> kitchen knife</li>

I used the following code but it doesn’t work as I’m expecting.

function replaceBetween(origin, startIndex, endIndex, insertion) {
    return (
        origin.substring(0, startIndex) + insertion + origin.substring(endIndex)
    );
}

Usage:

replaceBetween("<li>the <span>best</span> kitchen knife</li>", 4, 8, "nice");

Output:

<li>nice<span>best</span> kitchen knife</li>

Expected Output:

<li>The <span>nice</span> kitchen knife</li>

How to solve Master Mind using Genetic Algorithm

Welcome,
I had to make a bot for the mastermind game to solve it using AI,
well Donald Knuth’s algorithm is simple, but It takes more moves and is not efficient up to me.
So, after researching I found a paper and its code on solving mastermind with genetic algorithm.
But that paper is like a benchmark and doesn’t explain, as well as I don’t understand python!
Hence looking for a code on other languages (my preferred language is pure js),I found:

Link Language Disadvantage
LINK1 Javascript with Jquery Jquery is a problem more than that the three modes are confusing (I want only Human vs AI)
LINK2 React js React js is a problem more than that see the [My problem] below
LINK3 Java Again, see the [My problem] below

[My problem]=The way it calculates the output (black and white coins) is different
That is as you can see in the LINK1,

Output for
Guess:[2, 2, 5, 2]
Answer:[4, 5, 3, 5]

Output:-
Correct coin in, Correct position: 0
Correct coin in, Wrong position: 1
The above output is correct,


But the below output which is got for LINK2 & LINK3 code is wrong
Output for
Guess=[2, 2, 5, 2]
Answer=[4, 5, 3, 5]

Output:-
Correct coin in, Correct position: 0
Correct coin in, Wrong position: 2



I got these outputs by extracting the code part that the algorithm uses to check

Correct code, extracted from link1

prediction = [2, 2, 5, 2];
answer = [4, 5, 3, 5];
function testCode (combination, solution) {
    NUM_FIELDS = solution.length;
    var a = 0;
    var b = 0;
    var marked = [0, 0, 0, 0];
    for(var i = 0; i<NUM_FIELDS; i++) {
        if(combination[i] == solution[i]) {
            a++;
            marked[i] = 1;
        }
    }
    for(var i = 0; i<NUM_FIELDS; i++) {
        if(combination[i] != solution[i]) {
            for(var j = 0; j<NUM_FIELDS; j++) {
                if(i != j && 0 == marked[j] && combination[i] == solution[j]) {
                    b++;
                    marked[j] = 1;
                    break;
                }
            }
        }
    }   
    return [a, b];
}
console.log(testCode(prediction,answer));

Wrong code, extracted from link2 & link3

prediction = [2, 2, 5, 2];
answer = [4, 5, 3, 5];
function getMoveScore(input, answer) {
  let correctColorLocation = 0;
  let correctColorWrongLocation = 0;
  // correct color correct location
  for (let i = 0; i < input.length; i++) {
    if (input[i] === answer[i]) {
      correctColorLocation += 1;
    }
  }
  // correct color
  for (let i = 0; i < answer.length; i++) {
    var inputSet = new Set(input);
    if (inputSet.has(answer[i])) {
      correctColorWrongLocation += 1;
    }
  }
  correctColorWrongLocation -= correctColorLocation;
  const incorrect = 4 - correctColorWrongLocation - correctColorLocation;
  return [correctColorLocation,correctColorWrongLocation];
}
console.log(getMoveScore(prediction, answer));


Anyway this is not the problem, Main problem is

  • Everything is ok in LINK1 but the 3 modes are confusing
  • I am looking for a simple code that is console-based(not graphical),explanation&commented code is appreciated but not needed

Calculating HTML input using JavaScript

Hi I am trying to calculate the percentage using the input from the HTML input

let timeSpend = document.querySelector(".time_spend")

var fSubject = (50/timeSpend)*100;
var sSubject = (25/timeSpend)*100;
var tSubject = (25/timeSpend)*100;
window.alert(fSubject);

This is my HTML input that I have the type of number but I don’t know why it still not working

<input
          type="number"
          id="text-box"
          class="time_spend"
          placeholder="How much time do you have?"
        />

ReactJS vs Flutter

Which is better and which will be the best one in the future?Some said ‘Flutter already overtaked the whole reactJS’ and others said ‘It is only a matter of time that reactJS will overtake flutter again.’. It’s best to learn flutter or reactJS or both?

How does an array of numbers and its sorted version strictly equal to each other? [duplicate]

Let’s say we have an array of numbers in Javascript:

const arr = [1,3,2,6,5,3];

We sort it using the native sort method:

arr.sort(); // OR arr.sort((a, b) => a - b)

Now how do the unsorted and sorted array equal to one another?

console.log(arr === arr.sort()) // logs true 

I am aware the sort method does not create a new array, so they would both point to the same address on the memory.

However, their element order is different, and since arrays are list-like objects, with enumerable indices, the order of elements do matter unlike objects.

So, if all above is true, how are they strictly equal?

const arr = [1, 3, 2, 6, 5, 3];
arr.sort(); // OR arr.sort((a, b) => a - b)
console.log(arr === arr.sort()) // logs true

Exclude directory from webpack copy in vue CLI

I have a Vue3 project made with Vue CLI 5.0.1

My setup has a public folder where I have static assets that I need to serve, but it is very heavy (1GB of assets) so when I launch the npm run serve command I get the build stuck on [92%] sealing (asset processing copy-webpack-plugin).

I need so to exclude the public/resources directory from the copy-webpack-plugin.

I tried with the following config added in my vue.config.js:

    chainWebpack: (config) => {
    config.plugin("copy").tap(([options]) => {
      options[0].ignore.push("resources/**");
      return [options];
    });
 }

But I get this error:

ERROR TypeError: Cannot read property 'ignore' of undefined