Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

238
Vistas
How to add value of missing object after comparing to another array?

I have an array of months (var months), and I am trying to filter out and get the months that the array of object (var array1) does not have and add empty value of property 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}];`

Eg. array1 has the property value of Month: Jan, Feb, May and Jun, but I want to get the months that are missing and add value of 0 to property Avg like {Month: 'Mar', Avg: 0}, {Month: 'Apr', Avg: 0}, ... for the missing months comparing it with months array

Expected result of 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 Respuestas
Responde la pregunta

0

Use Array.map with 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);

Reference: Array, Nullish

about 4 years ago · Juan Pablo Isaza Denunciar

0

I think this should work pretty much!

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda