What is the best way to write if-then-else for a large data set in JavaScript? [closed]

I am trying to write conditional statements for a large data set in JavaScript.

Here is an example:

// two
if (age==2) {
 if (lifestyle==1) {
   calorie=1000
  }
 if (lifestyle==2) {
   calorie=2000
 }
 ....
 // three
 else if (age==3) {
  if (lifestyle==1) {
   calorie=1000
  }
 if (lifestyle==2) {
   calorie=2000
 }....
 // four...and so, until 100

Basically repeat the above several times. I am not an expert in JavaScript. While the above is working fine to get the results, I don’t think this may be the most efficient way to write if-then-else. Are there any other efficient options in JavaScript to do this?

jQuery: Merge dynamic html table cells with img attributes

I need to merge cells when it has the same value in the column. However, this only works when I have text value inside the cell. The problem is: I need the code to function when comparing “img src” attributes as well since one of the column contains image.

Ps: Let’s say I have 3 columns (colA: contains img attributes only, colB and colC contains text value). ColA should merge when the next row has the same img attributes.

My code looks as below:

$(function () {
                $.map($("tr:first td"), function (b, a) {
                    return $("tr td:nth-child(" + ++a + ")")
                }).forEach(function (b) {               
                    var a;
                    b.each(function (b, c) {
                        // if($("img", a) == $("img", c))
                        // if($(a).find("img").attr("src") == $(c).find("img").attr("src"))
                        
                        ($(a).find("img").attr("src") == $(c).find("img").attr("src")) && a && (a.textContent == c.textContent) ? ($(c).remove(), a.rowSpan++) : a = c
                    })
                })
            });

I know it is possible to compare img attributes, but my code won’t work. The code that I’ve commented were the ones that I have tried.

How to check if an element has a class using PHP in WordPress function.php file

I am trying to hide an element on the front-end and remember the user choice by creating a cookie in PHP.

Here is how I have it set up:

I have some HTML and JS scripts inside an HTML widget on the page on the front-end

<div id="training-banner"> training banner design here </div>
<button onclick="myFunction()" id="close-btn">X</button>

<script>
function myFunction() {
  var element = document.getElementById("training-alert");
  element.classList.add("hidebanner");
}
</script>

Then I have written the cookie function inside the function.php of the child theme:

add_action('init', function() {
    if (!isset($_COOKIE['training_banner_cookie'])) {
        setcookie('training_banner_cookie', 'showbanner', strtotime('+1 day'));
    }
    
    if (class_exists('hidebanner')){
        ?><style>#training-alert{display:none;}</style> <?php
        setcookie('training_banner_cookie', 'hidebanner', strtotime('+1 day'));
    }

    $cookieValue = $_COOKIE['training_banner_cookie'];
    if ($cookieValue == "hidebanner"){
        ?><style>#training-alert{display:none;}</style> <?php
    }
});

For some reason, the class_exists() PHP function does not work, any idea how this can be achieved?

Csurf (Cross Site Request Forgery) Protection in a pop up css login authentication modal in Pug/Express

I can’t seem to get my csurf token to work in my pop up strictly css modal, for authentication purposes. It works fine in a page (not in modal). I am using Pug view engine, express and cookie parser. Below is the relevant code, any suggestions would be appreciated, thank you.

layout.pug

       a(href="#open-modal")
        span Login
        div(id="open-modal" class="modal-window")
          div
            a(href="#" title="Close" class="modal-close") Close
            h1 Login
            div
              +errorSummaryList(errors)
              form(method="post" action="/get" class="nav__login")
                input(type="hidden" name="_csrf" value=csrfToken)
                label(for="username") Username:
                input(type="text" name="username" id="username")
                label(for="password") Password:
                input(type="password" name="password" id="password")
                button Submit
                button Demo User

auth.js

const { User } = require('./db/models');

function loginUser(req, res, user){
  req.session.auth = {
    userId: user.id
  };
  req.session.save(function () {
    res.redirect("/");
  });
  console.log(req.session)
};

async function restoreUser(req, res, next){

  if(req.session.auth){
    let { userId }= req.session.auth;
try{
  let user = await User.findByPk(userId);

  if(user){
    res.locals.authenticated = true;
    res.locals.user = user;
    console.log(res.locals)
    next();
  }
} catch(error){
  res.locals.authenticated = false;
  next(error);
}


}
  res.locals.authenticated = false;
  next();
}

function logoutUser(req,res){
  delete req.session.auth;
}

users.js

router.get('/login', csrfProtection, asyncHandler(async(req, res, next)=> {
  let user = User.build();
  res.render('user-login',{user, csrfToken: req.csrfToken()})
}));

router.post('/login',loginValidators, csrfProtection, asyncHandler(async(req, res, next)=>{
  const { username, password } = req.body;

  let errors = [];
  const validationErrors = validationResult(req);

  if(validationErrors.isEmpty()){

    const user = await User.findOne({
      where:{
        username
      }
    })

    if(user){
      console.log('found user')
      const isVerified = await bcrypt.compare(password, user.password.toString())

      if(isVerified){
        console.log("verified")
        loginUser(req, res, user)
        return;
        
      }
      errors.push("Username and/or password are incorrect. Try again. ");
    }
  }
  validationErrors.array().map(err => errors.push(err.msg));

  res.render('user-login',{errors, csrfToken: req.csrfToken()})
}));

app.js

const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const { sequelize } = require('./db/models');
const session = require('express-session');
const SequelizeStore = require('connect-session-sequelize')(session.Store);

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const { restoreUser } = require('./auth');
const { sessionSecret } = require('./config');

const app = express();

// view engine setup
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser(sessionSecret));
app.use(express.static(path.join(__dirname, 'public')));
// set up session middleware
const store = new SequelizeStore({ db: sequelize });

app.use(
  session({
    secret: sessionSecret,
    store,
    saveUninitialized: false,
    resave: false,
  })
  );

How can I get the last items from a nested array? [duplicate]

I was struggling to get the last object item from a nested array. I tried to implement flatMap, flat, filter, and splice. However, I can not still get the expected array.

const array = [
  [
    {
      date: "2020-02-25",
      total_cases: 18,
    },
    {
      date: "2020-02-26",
      total_cases: 32,
    },
    {
      date: "last-object",
      total_cases: 7,
    },
  ],
  [
    {
      date: "2020-02-26",
      total_cases: 4,
    },
    {
      date: "last-object",
      total_cases: 52,
    },
  ],
  [
    {
      date: "last-object",
      total_cases: 68,
    },
  ],
];

I have an array like the above. How can I get only the last-object total-case’s item into a new array?

Expected new array should be like this:

[7, 52, 68]

Thanks in advance!

Javascript: Mysql date and time duration

I have a little problem when filtering a record, what I want is the query will return true if the date is not in the record, the query result will only be false if the newDate(form) is in between the startDate(field) and the duration(field)

var newDate = "15/04/2022 10:07 AM"

var duration = 3600000

This is my current query

sql = "SELECT startDate FROM Event WHERE startDate BETWEEN '" + moment(newDate).startOf(`day`) + "' AND '" + moment(newDate).endOf(`day`) + "'
if(sql.length > 0){
  valid = true
}else{
   valid = false
}

record inside the database

enter image description here

Looping through an array using if then statements using JavaScript

I am very new here and new to code. I not know anyone who can help me with this and have watched allot of youtube videos on how to try and solve my problem.
I am trying to loop through the array below using if then and else statements and the function cardCounter. I want the the items in the array to individually appear on the screen and then disappear one after the other. Right now my array just looks like lines of text on a screen when opened in my browser.

This is my code:

 <script>
     const calm1 = [];
         calm1[0]= "Silence is the element in which great things fashion themselves 
          together. —Thomas Carlyle";
         calm1[1]= "Take a deep breathe in and count to 7 seconds ";
         calm1[2]= "Take a slow exhale out";
         calm1[3]= "Self-care is not selfish. You cannot serve from an empty vessel.– Eleanor Brown";
         calm1[4]= "Loneliness is a sign you are in desperate need of yourself.― Rupi Kaur,";
         calm1[5]= "do not look for healingat the feet of thosewho broke you― Rupi Kaur,";
         calm1[6]= "if you were born with the weakness to fall you were born with the strength to rise― Rupi Kaur";
         calm1[7]= "you kill your future by mourning the past― R.H. Sin";
         calm1[8]= "Our backs tell stories no books have the spine to carry― Rupi Kaur";
         calm1[9]= "what is stronger than the human heart which shatters over and over and still lives― Rupi Kaur";
         calm1[10]= "the world gives you so much pain and here you are making gold out of it- there is nothing purer than that― Rupi Kaur";
         calm1[11]= "fall in love with your solitude― Rupi Kaur";
         calm1[12]= "You do not just wake up and become the butterfly -Growth is a process.― Rupi Kaur";
         document.getElementById("calm").innerHTML = calm1;

     var words = document.getElementById('calm');
     var text = -1;
     function cardCounter () {
        text++;
        if (text<calm1.length) {
            words = calm1[text];
        }
        else {
            words = -1;
            clearInterval(intervalTimer);
        }

     ;}  
     var intervalTimer = setInterval(function(){cardCounter()},5000);

 </script>
 
 

.find always retuns `undefind`

I have a pathArray that contains a number of path’s (directory names) elements as a strings. I want to find the path that matches current file name

const filePath = this.pathArray.find((x) => {
  const testPath = join(x, fileName);
  if (fs.existsSync(testPath)) {
    return testPath;
  }
});

console.log(filePath); //should always have a value

However the return testPath is always undefined. Any ideas why?

Need help Making ajax request with correct URL and a crash on line 21

I am having issues with this code and I am not sure what to do, so any help would be greatly appreciated!! As stated in the title I am tryin to request a url but it keeps coming back with a long number attached to it (shown in picture) and I am getting a crash at line 21 saying that “Uncaught TypeError: Cannot read property ‘quote’ of undefined” pictured below as well.

My HTML can’t edit this

My HTML

My .js code with pictures of errors

$(function () {
$("#fetchQuotesBtn").click(function() {
const selectedTopic =$('#topicSelection option:selected').val();
const selectedCount =$('#countSelection option:selected').val();
fetchQuotes(selectedTopic,selectedCount);
 
});
});
 

URL error

Here is where I am trying to request the URL, the picture shows what I should be getting vs what I am getting

function fetchQuotes(topic,count) {
  $.ajax({
     url: "https://wp.zybooks.com/quotes.php?topic="+topic+"&count="+count,
  dataType: 'text',
  type: "GET",
  data: "",
  contentType: false,
  cache: false,
  processData:false,
  success: function(data) {

line21error

Below is line 21 the picture above is the error I am getting

var r_data = JSON.parse(data);

let html = "<ol>";

for (let c = 0; c < parseInt(count); c++) {
  html +=
    "<li>" +
    r_data[parseInt(c)]["quote"] +
    " - " +
    r_data[parseInt(c)]["source"] +
    " </li>";
}
html += "</ol>";

$("#quotes").html(html);

Redux dev tools showing user input password in plain text

After a form submission using Redux, I am able to see the plain text password in the dev tools meta section. Is this safe? Am I doing something wrong when passing the password down to the reducer? How can I make this more secure?

So in my userSlice I am creating an Async Thunk that accepts user input then grabs the user from my server/database.

export const setUserAsync = createAsyncThunk(
  'user/setUserAsync',
  async (payload, { rejectWithValue }) => {
    try {
      const response = await axios.post('/auth/login', payload);
      const { token, user } = response.data;
      console.log(response);
      localStorage.setItem('user', JSON.stringify(user));
      localStorage.setItem('token', token);
      return user;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

which works as intended. I am then calling the fulfilled reducer to set the user state.

[setUserAsync.fulfilled]: (state, action) => {
  state.user = action.payload;
  state.isLoggedIn = !!action.payload;
}

but in my dev tools I am seeing the following which is plain text of the password I input, in this case it is wrong, but when it’s right it shows it just the same.

password screenshot

Create a counter for “yes” and “no” selections from radio buttons using JavaScript

I’ve been reading the site’s question, but I haven’t found any that helps me find a solution to my problem:

I need to create a counter that shows how many times the “Yes” option was selected in the form, and how many times the “No” option was selected in the form. Then, I need to calculate a percentage based on the number of “Yes” selections against the total number of choices.

Here’s the HTML:

        <section>
        <h2>Cumplimiento 1</h2>
            <form class="form3">
            <fieldset class="Compliance">
                <label class="form3header1" for="complianceperc">Cumplimiento (%)</label>
                <span class="percentage" type="number" id="complianceperc" name="complianceperc"></span>

                <label class="form3item1" for="yescount">Sí (cantidad)</label>
                <span id="price" class="counter"></span>    
                
                <label class="form3item2" for="yescount">No (cantidad)</label>
                <span class="counter"></span>

                </fieldset>
            </form>
            
        </section>

And here’s the JavaScript (based on other answers in stackoverflow):

$('.counter').text($(':radio:checked').length);

$('input[type=radio]').change(function(){
  $('.counter').text($(':radio:checked').length);
});

And this is one of the radio button groups:

<label class="form4item1">1. ¿El Asesor de Servicio comienza a atender al Cliente en los primeros 2 minutos?</label>
            <input class="form4item1radio1" type="radio" name="question1" id="a" value="Accept">
            <input class="form4item1radio2" type="radio" name="question1" id="b" value="Reject">
            <textarea class="form4item1comment" placeholder="Escribe tus notas aquí"></textarea>

All I can get is a counter that shows the number of checked radio buttons, which is close but not quite what I need. I am a beginner in JavaScript, so while I realize I have much to learn, any help would be appreciated.

Thanks in advance for your help.

JavaScript merge (AJAX) array objects with the same keys

My application is MVC 5, I am using the following Ajax to generate an array:

$.ajax({
            type: "Post",
            url: '@Url.Action("Getthereport", "Surveys")',
            async: false,
            cache: false,
            dataType: "json",
            data: { 'test': "All" },
            success: function (result) {

                if (result && result.Grid.length > 0) {
                    for (let i = 0; i < result.Grid.length; i++) {
                        jsonData.push({
                            Question: result.Grid[i].Body,
                            QuestionId: result.Grid[i].QuestionId,
                            myData: { name: result.Grid[i].name, value: result.Grid[i].value }
                          });
                    };
                }
               },
            complete: function () {
               reduce();
            },
            error: function(err) {
                alert(err.status + " : " + err.statusText);
            }
        });

I generates the following:

var jsonData = [
            {
                Question: "Was the training useful?",
                QuestionId: 1,
                myData: [{ name: 'No', value: 1 }] },
            {
                Question: "Was the training useful?",
                QuestionId: 1 ,
                myData: [{ name: 'Yes', value: 1 }]
        }];

to merge the objects, I use:

const result = Object.values(jsonData.reduce((acc, obj) => {
  if (!acc[obj.QuestionId]) {
    acc[obj.QuestionId] = obj;
  } else {
    acc[obj.QuestionId].myData = acc[obj.QuestionId].myData.concat(obj.myData);
  }
  return acc;

Works great if the array is hardcoded and generates:

var jsonData = [
        {
            Question: "Was the training useful?",
            QuestionId: 1,
            myData: [{ name: 'No', value: 1 },
                     { name: 'Yes', value: 1 }] 
          }]; 

However, if the array is generated by Ajax call, I get the following error:

 acc[obj.QuestionId].myData.concat is not a function

I tried to run the reduce script on Ajax complete and directly both did not work.

Change Textinput value when rendering Using .map() React native

i am using map function to render my component which have textInput . I want to change value of textInput using onchangeText function.

 const [Value, setValue0] = useState('');
 //in my return i use :
                 <ViewDeatilCard1 key={id} setChangeText={(value)=>{`'setValue${id}${(value)}'`}} /> //this
                 <ViewDeatilCard1 key={id} setChangeText={()=>{`'setValue${id}'`}} /> //this
                 <ViewDeatilCard1 key={id} setChangeText={`'setValue${id}'`} /> //this
  // none of this work
 // in my component i use 
 export const ViewDeatilCard1 = ({
setChangeText
 }) => {
console.log(setChangeText,"setChangeText");
return (
    <View style={styles.container}>
        
            <View style={styles.body}>
            <FormInput
             style={styles.bodyText}
     
       labelText="Enter pick up loaction"
        iconName="null"
        onChangeText={setChangeText}
      />
            </View>
        </View>
    
)}

how can i change my value using this approach

trying to show the random words but cannot show double

i have an array that contains 5 of words. I’m about to show the random words from an array but can’t duplicate and by clicking the button. for example, ‘js’,’css’,’php’,’java’,’html’

words=['html','css','js','php','java'];
var currentWords=0;
var targetWords=words.length;
var temp=[];

while(currentWords < targetWords){
        var randomQue=Math.floor(Math.random() * words.length);
        console.log(randomQue)

        //check if the question already shown or not 
        if (temp[randomQue]){
             
        } else {
        }

        
        currentWords++;
        

    }