JavaScript to push value in empty index in array

JavascriptWeb DevelopmentObject Oriented Programming

We have an array that contains some empty values inside it like this −

const arr = [43,534534,645,64,,645,64,,645,,645,,65,,645,,64];

We are required to write an Array function pushAtEmpty() which takes in an element and pushes it at the first empty index it finds in the array it is used in context of. If there are no empty spaces, the element should be pushed at the last of the array.

Let’s write the code for this function. We will first search for the index of empty position and then replace the value there with the value we are provided with.

Example

const arr = [43,534534,645,64,,645,64,,645,,645,,65,,645,,64];
Array.prototype.pushAtEmpty = function(element){
   let index;
   for(index = 0; index < this.length; index++){
      if(arr[index] === undefined){
         this.splice(index, 1, element);
         break;
      };
   };
   if(index === this.length){
      this.push(element);
   }
};
arr.pushAtEmpty(23);
arr.pushAtEmpty(33);
arr.pushAtEmpty(43);
arr.pushAtEmpty(53);
arr.pushAtEmpty(63);
arr.pushAtEmpty(73);
arr.pushAtEmpty(83);
arr.pushAtEmpty(93);
console.log(arr);

Output

The output in the console will be −

[
   43, 534534, 645, 64,
   23, 645, 64, 33,
   645, 43, 645, 53,
   65, 63, 645, 73,
   64, 83, 93
]
raja
Published on 26-Aug-2020 09:44:34
Advertisements