How to loop through multiple arrays, within an array of arrays using a single value for an index?

I’m trying to solve a problem where you have an array

array = [[a,b,c],[e,f,g],[h,i,j]]

I want to loop through the first letter of the first array, then look at the first of all the other arrays then do a comparison whether they’re equal or not. I’m unsure how to do this given that a loop will go through everything in its array. I wrote a nested loop below, but I know it’s know it’s not the right approach. I basically want something that looks
like
if (array[0][0] == array[1][0] == array[2][0]), then repeat for each element in array[0]

  var firstWord = array[0];
  var remainderWords = array.slice(1); 
  for(var i = 0; i < firstWord.length; i++){
    for (var j = 0; i< remainderWords.length; j++){

      if firstWord[i] == remaindersWord[j][i]
    }

Any help would be appreciated.

hackerrank – min max sum test case fail

The problem I am doing is on hackerrank, and I don’t understand what I’m missing here feels like this should be working.

https://www.hackerrank.com/challenges/mini-max-sum/problem?isFullScreen=true

Test Case 0:
arr = [1, 2, 3, 4, 5];

Test Case 1:
arr = [7, 69, 2, 221, 8974];

function miniMaxSum(arr) {
    var temp = 0;
    var mini = 0;
    var max = 0;
    for (let i = 0; i < arr.length; i++) {
        temp += arr[i];
        if (i == arr.length - 2) {
            mini = temp;
        }
    }
    max = temp - arr[0];
    console.log(mini + ' ' + max);
}

Test case 1 fails
My output: 299 9266

Expected output: 299 9271

stack excedeed in recursive function for reading JSON key-value and creating a string to append to the DOM

I know there are a lot of similar questions here but they are different from mine. basically I have an Ajax call that return me an array of objects that are nested in more levels. the problem is that I don’t know neither how many the levels are nor the property names of them. so I made a recursive function for extracting the data from it and build a string that I’m going to append to the Dom after reading all the keys and values inside the object.
the json is an array with inside three objects that have inside of them arrays of objects sometimes.I wrote this code:

$.ajax({
      type:'GET',
      url:'/apiTlvArchive/tlvListAuditRecords',
      data:{
        xFilterObj:strObject
      },
      success:(result)=>{
        if(result.AuditRecords){
          AuditRecords=result.AuditRecords
          Docreatefiltersessiontable(AuditRecords)
        }
        
      },error:(error)=>{
        error.responseJSON.ErrorCode===9004 ? showErrorAlertMsg('Intervallo date seleionato troppo lungo') : showErrorAlertMsg('errore in list auditrecords')
        
      }
    })


  }

in the success callback I then call a function that is going to configure the table(I use datatables plugin) and inside this function I call the recursive function for reading the Json and creating a string that is gonna be appended to the DOM. the code is as follows:

function Docreatefiltersessiontable(AuditRecords){//crea tabella in tab filtra sessione
          let tablestring=''
          tablestring+=`<thead>
          <tr><th>Parametro</th><th>Valore</th></tr>
          </thead><tbody>`
         tablestring+= processObject(AuditRecords)
         tablestring+='</tbody>'
         document.getElementById('FiltersessionTable').innerHTML=tablestring
         FiltersessionTableinstance= $("#FiltersessionTable").DataTable({
          scrollY: 500,
          scrollX: false,
          scrollCollapse: false,
          deferRender: true,
          paging: true,
          ordering: false,
          searching: true,
          info: false,
          searchDelay: 350,
          pageLength: 50,
          columnDefs: [
            {
              "width": "15%",
              "targets": 0
            },
            {
              "width":"12%",
              "targets":1

            },
          ]
        });
  }

and finally the recurisve function:

function processObject(jsonObject) {
    let strSource=''
    for (var property in jsonObject) {
        if (jsonObject.hasOwnProperty(property)) {
          if (typeof (jsonObject[property]) == 'object') {
            strSource+=processObject(jsonObject[property]);
           // processObject(jsonObject[property]);
          }
          if(isNaN(property) && typeof(jsonObject[property])!=="object"){//voglio escludere indici e object di object
           strSource+=`<tr>
                   <td>${property}</td>
                   <td>
                     ${jsonObject[property]}
                   </td>
                 </tr>`
           
          }
        }
      }
      return strSource;
  }

I get the stack exceedeed error only when I try to create the string inside of the function when the objects are a little more than usual. the fact is that the recursive function works fine for just reading the keys and values, but if i try to create something like the string, there’s always the point where is gonna cause the stack excedeed error.I need to do a recursive function cause I don’t know prior the keys of this Json. Any idea on how to fix this problem? is there another solution or recursion is the only one I have?

Making form submission asynchronous

I currently have a form with a few variables like username, password, and email which sends the data to a node.js server. Before sending the data, I have a few checks such as whether the inputs are valid and whether the email already exists in my file. The checking aspect of my code works, however the javascript function which I use to check returns before opening the file to check for duplicate emails. I feel that if I could somehow make the onsubmit function asynchronous, that would help.

Here is my code and the segment where I check for duplicate emails is near the end:

<html>
  <body>

    <form id='form' action="/signup.html" method="POST" onsubmit="return submitIt();">
      <div style="text-align:center">
        <label for="name">Full Name</label><br>
        <input type="text" size="100" id="name" name="name" placeholder="Enter Your Full Name: "><br><br>
        <label for="email">Email</label><br>
        <input type="text" size="100" id="email" name="email" placeholder="Enter Your Email: "><br><br>
        <label for="password">Password</label><br>
        <input type="text" size="100" id="password" name="password" placeholder="Enter Your Password: "><br><br>
        <button type="submit" id="submit">Submit</button>
      </div>
    </form>
  </body>
  <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
        var ret = true;
        async function submitIt() {
            let name = document.getElementById("name").value;
            let email = document.getElementById("email").value;
            let password = document.getElementById("password").value;

            if (name == "" || name.length < 4) {
                document.getElementById("name").value = "";
                document.getElementById("name").placeholder = "Please enter a real name";
                ret = false;
            }
            if (email == "" || email.length < 4) {
                document.getElementById("email").value = "";
                document.getElementById("email").placeholder = "Please enter a real email";
                ret = false;
            }
            if (ret) {
                let found = false;
                for (let i = 0; i < email.length; i++) {
                    if (email[i] == '@') {
                    found = true;
                    }
                }
                if (!found) {
                    document.getElementById("email").value = "";
                    document.getElementById("email").placeholder = "Please enter a real email";
                    ret = false;
                }
            }

            if (password.length < 5) {
                document.getElementById("password").value = "";
                document.getElementById("password").placeholder = "Password must be atleast 5 characters.";
                ret = false;
            }

            await $.ajax({
                type:"POST",
                url:'/getUsers',
                dataType: "text",
                success: function(content) {
                    let contents = content.split('n');
                    for (let i = 0; i < contents.length; i += 3) {
                        if (contents[i] == email) {
                            document.getElementById("email").value = "";
                            document.getElementById("email").placeholder = "Email already in use.";
                            ret = false;
                        }
                    }
                }
            });
            return ret;
        }
        
    </script>
  </head>
</html>

Any help would be greatly appreciated!

Passing variable offset in Gradient element of Snap SVG

I was working on showing a tank’s water level in snap svg. I have a square tank as:

<!DOCTYPE html>
<html>
<body>

<svg id = "svg" width="1000" height="1000">
  <rect id = "tank" x="0" y="0" height = "100" width = "100" fill = "none" stroke = "black" />
</svg>

</body>
</html>

Now I had to show the water level in this tank using snap SVG. I have a percent variable in snap SVG, the percentage of water in the tank.

How to do this? I used gradients and the same offset value for both colours (60 in this case). Is there any method to use this variable in s.gradient? Or am I doing this wrong way?
http://jsfiddle.net/8obgka1r/

filter and includes in array, how does that work?

I’m trying to understand how filter() and includes() work with arrays in javascript but english isn’t my native language so I would really appreciate it if someone could explain the example below to me like I was 5:

const removeFromArray = function(...num) {
    let array = num[0];
    return array.filter(val => !num.includes(val))
};

This function takes an array and some other arguments then removes the other arguments from that array for example removeFromArray([1, 2, 3, 4], 3) should remove 3 and return [1,2,4]

How does this part work?

return array.filter(val => !num.includes(val))

Why the exclamation mark and also how do those two methods work together?

Recursive function JS, returning undefined [duplicate]

I did recursive function to add digits of number till i got one-digit number:
4564 => 4+5+6+4=19 => 1+9=10 => 1+0=1
When i check next steps everything seems fine, but function after all repeats returning undifned…

function digital_root(n) {
      let table = String(n);
      let sum=0;
      for(let i=0; i<table.length; i++)
        {
        sum = sum + Number(table[i]);
        }
      if(sum>=10){console.log(sum); digital_root(sum);}
      else {console.log(sum); return sum;}
    }
    digital_root(4564);

What do I press to autocomplete the “——-” in console.log() and add a duplicate line?

Starting at 2:15 in the below vscode tutorial video, he types “console.log(“, then I am assuming he presses a button that autocomplete the entry to “console.log(“——————“); which duplicates below.

When I type “console.log(” no autocomplete options appear. Additionally, even if I duplicate his code manually as below:

console.log("-------------------");
console.log("Rise & Shine!");
console.log("Ready for a new day!");
console.log("-------------------");

And press F5, a new window pops open titled “[Extension Development Host] settings.json – Visual Studio Code and returns the following code:

{
    "workbench.colorTheme": "Default High Contrast",
    "workbench.startupEditor": "none",
    "files.autoSave": "afterDelay",
    "explorer.confirmDelete": false
}

https://www.youtube.com/watch?v=B-s71n0dHUk&t=200s

Extensions installed:
JavaSCript (ES6) code snippets
Javascript Debugger
Code Runner
json
npm intellisense

How can I type a resulting function based on the return type of an argument function

I have two functions:

export const processCar = (params: IParams): Car => {
    // ...
}

export const processBoat = (params: IParams): Boat => {
    // ...
}

I have another function to which the first two functions will be passed as arguments:

const processOrNull = (func: any): any => {
    const newFunc = (params: IParams): any => {
        // Perform some check. If it fails, return null. If it passes...

        return func(params);
    }
    return newFunc;
}

export const processCarOrNull = processOrNull(processCar);  // (IParams) => Car | null;
export const processBoatOrNull = processOrNull(processBoat);    // (IParams) => Boat | null;

I want the result from processOrNull to be typed as either (IParams) => Car | null or (IParams) => Boat | null, depending on whether the passed function returns a Car or a Boat.

Can I do this with generics and if so, how?

no body in fetch put for node express

I cannot get the body correct on the server. If I use content type of json, I get an empty body, if I use urlencoded I get the body but not parsed. Looks like this { { “title”: “New Title” }: ” } I would expect to just access a property on the body like so, req.body.title. I’m using latest version of node and express.

Client

function editMovies() {
    //var putMethod = { method: 'PUT', headers: { "Content-Type": "content-type: application/json" } };
    var putMethod = { method: 'PUT', headers: { "Content-Type": "application/x-www-form-urlencoded" } };
    putMethod.body = JSON.stringify({ "title": "New Title" });
    fetch("/api/movies/2", putMethod).then(function (response) {});
}

Server

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.put('/api/movies/:id', function (req, res) {
    var id = req.params.id;
    console.log('put called with:' + req.body.title);
});

Is there a way where i can get information from an Object within an Array of an API with a function so that i can show it on the HTML?

I’m trying to get reandom info frinm the API of Jojo’s. I want to select specific parts of the array that i get from the API so that i show only the useful information that it provides from the characters. But i cant manage to get the info of the part from “stand_type” o any specific section of the array, please someone help me with this.

My Code so far:

async function getCharacter(){
const number = getRandomNumber();
var infos = await 
fetch('https://jojoapi.herokuapp.com/DiamondIsUnbreakable').then(response => response.json());
console.log("Number = " + number);
console.log(infos[number])}

JavaScript calling async function at the same time with different parameters

I have an async function “A” that performs fetch await, waits for result, then does something with the result.

If I call that async function “A” with 2 different parameters at the same time, wanting to fetch 2 different things, it will go ahead and perform only one of them (I guess the one that came in first)

The workaround fix is to have 2 different functions “A” and “B” and call them separately with different parameters…

But is it possible to call function “A” with different parameters at the same time, have it fetch await BOTH and then do something with both results all within one function?

Hope this makes sense.

Thank you for your valuable thoughts.

Editable input issue in reactjs table

I am trying to build an editable table in reactjs.

First I map state data and build table body.

Now I want when I click the td that particular td turns into input and when I click outside that td it again becomes span as per my condition.

Here is the code:

import { useRef, useState } from 'react'
import useClickOutside from '../../hooks/useOnClickOutside'

const data = [
  {
    studentId: '01',
    name: 'John Doe',
    email: '[email protected]',
    editMode: false,
  },
  {
    studentId: '03',
    name: 'Mike',
    email: '[email protected]',
    editMode: false,
  },
]

const EditableTable = () => {
  const [studentsData, setStudentsData] = useState(data)

  const clickRef = useRef()

  const onClickOutside = () => {
    console.log('clicked outside')
    setStudentsData(data)
  }

  useClickOutside(clickRef, onClickOutside)

  const handleEditableTextField = (studentId) => {
    const activeMode = studentsData.map((item) =>
      item.studentId === studentId ? { ...item, editMode: true } : item
    )

    setStudentsData(activeMode)
  }

  const onChange = (e, studentId) => {
    const { name, value } = e.target
    console.log({ name, value })

    const editData = studentsData.map((item) =>
      item.studentId === studentId && name ? { ...item, [name]: value } : item
    )

    setStudentsData(editData)
  }

  return (
    <div className="container" ref={clickRef}>
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Email</th>
          </tr>
        </thead>
        <tbody>
          {studentsData.map(({ studentId, name, email, editMode }) => (
            <tr key={studentId}>
              <td onClick={() => handleEditableTextField(studentId)}>
                {editMode ? (
                  <input
                    name="name"
                    type="text"
                    value={name}
                    onChange={(e) => onChange(e, studentId)}
                  />
                ) : (
                  <span>{name}</span>
                )}
              </td>
              <td onClick={() => handleEditableTextField(studentId)}>
                <div>
                  {editMode ? (
                    <input
                      name="email"
                      type="email"
                      value={email}
                      onChange={(e) => onChange(e, studentId)}
                    />
                  ) : (
                    <span>{email}</span>
                  )}
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

The problem is when I click td that complete row becomes editable.
Struggling with handleEditableTextField function and clickRef

I hope I am clear.

Depixelize an image

i’m looking for a way to depixelize an image that i pixelize with this code. I want to know if i can change the samplesize variable value with an addeventlistener or something like that. Thanks for reading this and i hope that someone will help me !


let c = document.createElement("canvas")
let img1 = new Image()

img1.onload = function() {
    document.getElementById("img1").remove()
    w = img1.width
    h = img1.height

    c.width =  w
    c.height = h
    ctx = c.getContext("2d")
    ctx.drawImage(img1, 0, 0,)

    let pixelarr = ctx.getImageData(0,0,w,h).data
    let samplesize = 10
    
   

  
    for(let y=0;y<h;y+=samplesize)
        for(let x=0;x<w;x+=samplesize) {
            let p = (x+(y*w))*4
            ctx.fillStyle = "rgba(" + pixelarr[p] + "," + pixelarr[p+1] + "," + pixelarr[p+2] + "," + pixelarr[p+3] + ")"
            ctx.fillRect(x,y,samplesize, samplesize)
        }

    

    let img2 = new Image()
    img2.src = c.toDataURL("img/jpeg")
    img2.width = 600
    document.body.appendChild(img2)

  
    }
    

img1.src = document.getElementById("img1").src

Writing to a local json file with JS in an HTML tag

I am trying to write to a local json file with javascript, as of now I am using the fetch api in the post method to do so, but it returns error 405. It also returned error 405 when I used the put method. I know you can do it in Node.js, but I can’t figure out how to use it. If the answerer could tell me how to use Node.js for a website that would work as well.

fetch('./test.json', {
      method: 'POST',
      body: JSON.stringify(myData),
      headers: {
                'Content-Type': 'application/json'
               }
})