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

JavascriptWeb DevelopmentObject Oriented Programming

We are given a months array, which 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 at that place.

For example −

Intput → [5, 7, 9]
Output → [0, 0, 0, 0, 5, 0, 7, 0, 9, 10, 0, 0]

Now, let’s write the code −

Example

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

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.

Output

The output in the console for the above code will be −

[
   0, 0, 0, 0, 0,
   6, 7, 0, 0, 10,
   0, 12
]
raja
Published on 20-Aug-2020 05:59:15
Advertisements