Algorithm to dynamically populate JavaScript array with zeros before and after values

We are given a months array, which contains elements less than 12, where each element will be between 1 and 12 (both inclusive). Our job is to take this array and create a full months array with 12 elements. If the element is present in the original array we use that element, otherwise we use 0 at that place.

For example:

Input ? [5, 7, 9]
Output ? [0, 0, 0, 0, 5, 0, 7, 0, 9, 0, 0, 0]

Now, let's write the code:

Using Array.includes() Method

const months = [6, 7, 10, 12];
const completeMonths = (arr) => {
    const completed = [];
    for(let i = 1; i <= 12; i++){
        if(arr.includes(i)){
            completed.push(i);
        }else{
            completed.push(0);
        }
    };
    return completed;
};
console.log(completeMonths(months));
[
    0, 0, 0, 0, 0,
    6, 7, 0, 0, 10,
    0, 12
]

We iterated from 1 to 12, kept checking if the original array contains the current element. If yes, then we pushed that element to the new array; otherwise, we pushed 0 to the new array.

Using Set for Better Performance

For larger arrays, using a Set provides better performance than includes():

const months = [3, 6, 9, 12];
const completeMonthsOptimized = (arr) => {
    const monthsSet = new Set(arr);
    const completed = [];
    
    for(let i = 1; i <= 12; i++){
        completed.push(monthsSet.has(i) ? i : 0);
    }
    return completed;
};
console.log(completeMonthsOptimized(months));
[
    0, 0, 3, 0, 0,
    6, 0, 0, 9, 0,
    0, 12
]

Using Array.from() with Map Function

A more functional approach using Array.from():

const months = [1, 4, 8, 11];
const completeMonthsFunctional = (arr) => {
    const monthsSet = new Set(arr);
    return Array.from({length: 12}, (_, i) => 
        monthsSet.has(i + 1) ? i + 1 : 0
    );
};
console.log(completeMonthsFunctional(months));
[
    1, 0, 0, 4, 0,
    0, 0, 8, 0, 0,
    11, 0
]

Performance Comparison

Method Time Complexity Best For
includes() O(n × m) Small arrays
Set.has() O(n + m) Larger arrays
Array.from() O(n + m) Functional style

Conclusion

This algorithm creates a 12-element array with original values in their positions and zeros elsewhere. Use includes() for simplicity or Set for better performance with larger datasets.

Updated on: 2026-03-15T23:18:59+05:30

180 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements