javascriptarrays

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},
];

Solution

  • 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);