Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill in missing months in an array using javascript

Is there a way how can i complete missing month and sale in an incomplete array.

sometimes i get a query like this:

var sales = [

    {'month': '04', 'sale': 126},
    {'month': '06', 'sale': 165},
    {'month': '07', 'sale': 10},
    {'month': '08', 'sale': 20},
    {'month': '09', 'sale': 211},
    {'month': '10', 'sale': 27},
    {'month': '11', 'sale': 112},
];

and i need to add the missing months with sale: 0.

I thought i can make a second array with all months and then compare this two arrays and pick the duplicates to the array with all months:

var compareArray = [

    {'month': '01', 'sale': 0},
    {'month': '02', 'sale': 0},
    {'month': '03', 'sale': 0},
    {'month': '04', 'sale': 0},
    {'month': '05', 'sale': 0},
    {'month': '06', 'sale': 0},
    {'month': '07', 'sale': 0},
    {'month': '08', 'sale': 0},
    {'month': '09', 'sale': 0},
    {'month': '10', 'sale': 0},
    {'month': '11', 'sale': 0},
    {'month': '12', 'sale': 0},
];
like image 295
Greg Ostry Avatar asked Sep 04 '26 05:09

Greg Ostry


2 Answers

Instead of pre-defining the 12-entries array, you could use Array(12).keys() and use Array.from to map that to the desired output:

var sales = [{'month': '04', 'sale': 126}, {'month': '06', 'sale': 165}, {'month': '07', 'sale': 10},  {'month': '08', 'sale': 20}, {'month': '09', 'sale': 211}, {'month': '10', 'sale': 27}, {'month': '11', 'sale': 112}];

sales = Array.from(Array(12).keys(), month => 
    sales.find(sale => +sale.month === month+1) || { month: ("0"+(month+1)).substr(-2), sale: 0 }
);

console.log(sales);

Edit in 2025: With the addition of iterator helper methods in ECMAScript 2025, this can be rewritten as a chain:

let sales = [{'month': '04', 'sale': 126}, {'month': '06', 'sale': 165}, {'month': '07', 'sale': 10},  {'month': '08', 'sale': 20}, {'month': '09', 'sale': 211}, {'month': '10', 'sale': 27}, {'month': '11', 'sale': 112}];

sales = Array(12).keys().map(month => 
    sales.find(sale => +sale.month === ++month) ?? { month: ("0"+month).substr(-2), sale: 0 }
).toArray();

console.log(sales);
like image 148
trincot Avatar answered Sep 06 '26 18:09

trincot


An approach based on .map and .find array methods

const data = [
    {'month': '04', 'sale': 126},
    {'month': '06', 'sale': 165},
    {'month': '07', 'sale': 10},
    {'month': '08', 'sale': 20},
    {'month': '09', 'sale': 211},
    {'month': '10', 'sale': 27},
    {'month': '11', 'sale': 112},
];

const result = [...Array(12)].map((m, i) => {
  const month = i < 9 ? '0' + (i + 1) : String(i + 1);
  return data.find(d => d.month === month) || { month, sale: 0 };
});
like image 43
dhilt Avatar answered Sep 06 '26 17:09

dhilt