Inserting element at falsy index in an array - JavaScript


We are required to write an Array function, let’s say, pushAtFalsy() The function should take in an array and an element. It should insert the element at the first falsy index it finds in the array.

If there are no empty spaces, the element should be inserted at the last of the array.

We will first search for the index of empty position and then replace the value there with the value we are provided with.

Example

Following is the code −

const arr = [13, 34, 65, null, 64, false, 65, 14, undefined, 0, , 5, ,
6, ,85, ,334];
const pushAtFalsy = function(element){
   let index;
   for(index = 0; index < this.length; index++){
      if(!arr[index] && typeof arr[index] !== 'number'){
         this.splice(index, 1, element);
         break;
      };
   };
   if(index === this.length){
      this.push(element);
   }
};
Array.prototype.pushAtFalsy = pushAtFalsy;
arr.pushAtFalsy(4);
arr.pushAtFalsy(42);
arr.pushAtFalsy(424);
arr.pushAtFalsy(4242);
arr.pushAtFalsy(42424);
arr.pushAtFalsy(424242);
arr.pushAtFalsy(4242424);
console.log(arr);

Output

This will produce the following output in console −

[
   13,      34,     65,
    4,      64,     42,
   65,      14,    424,
    0,    4242,      5,
42424,       6, 424242,
   85, 4242424,    334
]

Updated on: 18-Sep-2020

121 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements