Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
Encuentra los meses que faltan en la matriz js

tengo la siguiente matriz

 [ { Month: '2021-05', Count: 36 }, { Month: '2021-06', Count: 1048 }, { Month: '2021-07', Count: 572 }, { Month: '2021-09', Count: 3 }, { Month: '2021-12', Count: 52 }, { Month: '2022-01', Count: 4 }, { Month: '2022-02', Count: 273 }, { Month: '2022-04', Count: 96 } ]

donde me faltan unos meses. Sé cuántos meses se necesitan (podrían ser 12 o podrían ser más o menos) y necesito que los meses que faltan (como 2021-08 en este caso) se agreguen con un conteo de 0. ¿Cómo hacerlo?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Aquí hay un enfoque puro y funcional que creará una nueva matriz con nuevos elementos, insertando todos los meses que faltan en orden. El código incluye algunos comentarios que explican el procedimiento:

 const parseDate = str => str.split('-').map(Number); const formatDate = (year, month) => `${year}-${String(month).padStart(2, '0')}`; function createContinuousMonthCounts (array) { const all = []; // get initial year/month values from first item let [year, month] = parseDate(array[0].Month); const advanceDate = () => { month += 1; if (month > 12) { year += 1; month = 1; } }; for (const item of array) { const [y, m] = parseDate(item.Month); // while the current month is not equal to the current item's month, // create an entry for the month, append it, and advance to the next month while (year !== y || month !== m) { all.push({Month: formatDate(year, month), Count: 0}); advanceDate(); } // after we're up to date, add the current item and advance the date all.push({...item}); advanceDate(); } return all; } const array = [ { Month: '2021-05', Count: 36 }, { Month: '2021-06', Count: 1048 }, { Month: '2021-07', Count: 572 }, { Month: '2021-09', Count: 3 }, { Month: '2021-12', Count: 52 }, { Month: '2022-01', Count: 4 }, { Month: '2022-02', Count: 273 }, { Month: '2022-04', Count: 96 }, ]; const all = createContinuousMonthCounts(array); for (const {Month, Count} of all) console.log(Month, Count);

about 4 years ago · Juan Pablo Isaza Relatório

0

Solo un tiro en la oscuridad (considere agregar algo de código a su pregunta):

 const months = [ { Month: '2021-05', Count: 36 }, { Month: '2021-06', Count: 1048 }, { Month: '2021-07', Count: 572 }, { Month: '2021-09', Count: 3 }, { Month: '2021-12', Count: 52 }, { Month: '2022-01', Count: 4 }, { Month: '2022-02', Count: 273 }, { Month: '2022-04', Count: 96 } ]; const neededMonths = [ "2021-01","2021-02","2021-03","2021-04","2021-05","2021-06","2021-07","2021-08","2021-09","2021-10","2021-11","2021-12" ] const missedMonths = []; months.map( m => { if(neededMonths.indexOf(m.Month) == -1 ){ missedMonths.push(m.Month); } }); console.log(missedMonths);

about 4 years ago · Juan Pablo Isaza Relatório

0

Primero necesita un método para encontrar todos los meses entre un rango, luego repita todos los meses y agregue los que faltan con el count: 0 :

 const months = [ { Month: '2021-05', Count: 36 }, { Month: '2021-06', Count: 1048 }, { Month: '2021-07', Count: 572 }, { Month: '2021-09', Count: 3 }, { Month: '2021-12', Count: 52 }, { Month: '2022-01', Count: 4 }, { Month: '2022-02', Count: 273 }, { Month: '2022-04', Count: 96 } ] const firstMonth = months.at(0).Month; const lastMonth = months.at(-1).Month; const [initialYear, initialMonth] = firstMonth.split('-'); const [endingYear, endingMonth] = lastMonth.split('-'); const allMonths = []; let currentMonth = initialMonth; let currentYear = initialYear; while (`${currentYear}-${(''+currentMonth).padStart(2, '0')}` !== lastMonth) { allMonths.push(`${currentYear}-${(''+currentMonth).padStart(2, '0')}`); currentMonth++; if (currentMonth === 13) { currentMonth = 1; currentYear++; } } allMonths.forEach(month => { if (!months.find(m => m.Month === month)) { months.push({Month: month, count: 0}); } }); console.log(months);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda