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

236
Views
¿Cómo agregar valor al objeto faltante después de compararlo con otra matriz?

Tengo una matriz de meses ( var months ), y estoy tratando de filtrar y obtener los meses que la matriz de objetos ( var array1 ) no tiene y agregar un valor vacío de la propiedad Avg

 var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var array1 = [{Month: 'Jan', Avg: 10},{Month: 'Feb', Avg: 20}, {Month: 'May', Avg: 50},{Month: 'Jun', Avg: 60}];`

P.ej. array1 tiene el valor de propiedad de Month: Jan , Feb , May and Jun , pero quiero obtener los meses que faltan y agregar el valor 0 a la propiedad Avg como {Month: 'Mar', Avg: 0}, {Month: 'Apr', Avg: 0}, ... para los meses que faltan comparándolos con la matriz de months

Resultado esperado de array1:

 [{Month: 'Jan', Avg: 10}, {Month: 'Feb', Avg: 20}, {Month: 'Mar', Avg: 0}, {Month: 'Apr', Avg: 0}, {Month: 'May', Avg: 50}, {Month: 'Jun', Avg: 60}, {Month: 'Jul', Avg: 0}, {Month: 'Aug', Avg: 0}, {Month: 'Sep', Avg: 0}, {Month: 'Oct', Avg: 0}, {Month: 'Nov', Avg: 0}, {Month: 'Dec', Avg: 0}];
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Usar Array.map con Array.find

 const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; const array1 = [{Month: 'Jan', Avg: 10},{Month: 'Feb', Avg: 20}, {Month: 'May', Avg: 50},{Month: 'Jun', Avg: 60}]; const result = months.map(m => array1.find(a => a.Month === m)??{Month: m, Avg: 0}); console.log(result);

Referencia: Array , Nullish

about 4 years ago · Juan Pablo Isaza Report

0

¡Creo que esto debería funcionar bastante!

 var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; var array1 = [{ Month: "Jan", Avg: 10 }, { Month: "Feb", Avg: 20 }, { Month: "May", Avg: 50 }, { Month: "Jun", Avg: 60 }, ]; let finalArr = []; months.filter((e) => { let index = array1.findIndex((ele) => ele.Month == e); if (index >= 0) { finalArr.push(array1[index]); } else { finalArr.push({ Month: e, Avg: 0 }); } }); console.log(finalArr);

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!