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.

Understanding Falsy Values

In JavaScript, falsy values include: null, undefined, false, 0, "" (empty string), and NaN. However, since 0 is a valid number, we'll exclude it from our falsy check.

Implementation

Here's how we can implement the pushAtFalsy() method:

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(!this[index] && typeof this[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);
[
   13,      34,     65,
    4,      64,     42,
   65,      14,    424,
    0,    4242,      5,
42424,       6, 424242,
   85, 4242424,    334
]

How It Works

The function iterates through the array looking for falsy values that are not numbers (to preserve 0 values). When it finds a falsy position like null, undefined, or empty slots, it replaces that position with the new element using splice().

If no falsy positions are found, the element is pushed to the end of the array using push().

Key Points

  • The method modifies the original array
  • Numbers like 0 are preserved as valid values
  • Empty array slots (sparse arrays) are considered falsy positions
  • Elements are inserted at the first available falsy position

Conclusion

The pushAtFalsy() method provides a way to fill empty or falsy positions in arrays while preserving numeric zeros. This is useful for maintaining array structure while replacing unwanted falsy values.

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

246 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements