Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

398
Views
Cómo extraer correctamente un valor definido de una matriz en un bucle (sin restablecer la variable constantemente)

En mi siguiente ejemplo, estoy tratando de extraer una variable de las entradas ("Reservas") que ha realizado el usuario. Si uno se hizo en un feriado de Pascua, configuro una celda en la base de datos con la fecha si no se establece el valor = "", por ejemplo Easteryear = "2022" || Easteryear = "" en la base de datos. Pero me resulta difícil extraer el último valor que definió. sin sobrescribirlo, la siguiente iteración del ciclo

El ejemplo de los datos que estoy buscando es: id:1 Easteryear ="2021" || id:2 Easteryear ="2022" || id:3 Easteryear ="" Quiero el 2022. Pero mis valores siguen estableciéndose en Null/NaN

Es más probable que mi enfoque de esto esté lejos de ser correcto, pero necesito ayuda para extraer el valor más reciente que no está vacío en el ciclo (si puedo hacerlo fuera de un ciclo sería increíble, sin embargo, necesito obtener ese valor para poder establecer otra variable para una comparación posterior)

Código corto TLDR: Intenté crear una verificación para ver si no se encontraron valores (AkA Easteryear está vacío en todas las entradas) Cree un valor para el usuario como si estuviera aquí, está reservando un valor en Pascua. Luego busque el último y configure userEasteryear

 if(this.personalEntries && this.personalEntries.length){ this.personalEntries.forEach(az => { if(az.easterYear == null || az.easterYear == "" && easterindex <= 1){ easterindex++; this.easterYear = year.toString(); return; //Trying to break out oft he loop if this happens, Its a bad idea Thinking about it now. }else{ var foundEasterYear = parseInt(az.easterYear); if(foundEasterYear !== NaN ){ userEasteryear = foundEasterYear; //My last ittiration of the if I kept getting leaks } az.inbet.forEach(i => { var x = (i.month+"-"+i.day+"-"+i.year); personalInbet.push(x);//This is a Temorary Array to Set the Dates Inbtw Start/End Dates }); } });

Estructura de entradas personales:

  • Apellido
  • Fecha de inicio
  • Fecha final
  • InBetween[] //Array de fechas desde la fecha de inicio hasta la fecha de finalización.
  • Semana Santa
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Entonces, si lo entiendo correctamente, proporcione una lista de PersonalEntries que desea devolver el año más alto que se especifica. Entonces es simplemente similar a

Encontrar el valor máximo de un atributo en una matriz de objetos

 const data = [ {id:1, Easteryear: "2021"}, {id:2, Easteryear: "2022"}, {id:3, Easteryear: ""} ] function getHighestField(objArray, fieldName) { return Number( Math.max.apply( Math, objArray?.map(o => o[fieldName] || 0), ) || 0, ); } console.log(getHighestField(data, 'Easteryear'));

si quieres el objeto completo

 const data = [ {id:1, Easteryear: "2021"}, {id:2, Easteryear: "2022"}, {id:3, Easteryear: ""} ] function getHighestField(objArray, fieldName) { return objArray.reduce((a,b)=>a[fieldName]>b[fieldName]?a:b); } console.log(getHighestField(data, 'Easteryear'));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!