Removing all the empty indices from array in JavaScript


Given there is an array with some empty indices and need to remove those empty indices from array.

Let’s look into the input output scenarios –

Consider there is an array with some empty indices. Now we need to exclude them and return the elements which are having only truthy values.

Array = [22, 45, , 56, 71, , 10];
Output = [22, 45, 56, 71, 10] 

As we can see in the output, the indices which are empty in the array got removed. We can achieve the above task by using several methods, let’s look into the approaches to solve it.

Using filter() method

The filter() method in JavaScript will create a new array with the elements that satisfied the condition given by the function. This method will not execute for empty elements and also will not change or modify the existing array.

Syntax

Following is the syntax of filter() method in JavaScript,

array.filter(function(currentValue index, arr));

Parameters

  • The function() parameter is a function to iterate for every array element.

  • CurrentValue parameter, this will be the value of the current element.

  • Index parameter, this will be the index of the current element.

  • The Arr parameter will be the array of the current element.

This filter() method will return a new array containing the elements which satisfied the condition in function. Will return an empty array if no elements passed the condition.

Example

In the example below, we have an array with empty indices. We have used filter() method to remove empty indices. We have called the filter() method and passed a function into it. for each iteration of the function in the array, it will return the current item. Now it will filter all the false values(empty indices) and return a new array containing truthy items in the array.

<!DOCTYPE html>
<html>
<head>
   <title>Removing all the empty indices from array</title>
   <button onClick = "fun()">Click! </button>
   <p id = "para"> </p>
</head>
<body>
   <script>
      const array = ['Hello', 'Tutorialspoint', , , , 23, , 5, 7];
      function fun(){
         const res = array.filter(item => {
            return item;
         });
         document.getElementById("para").innerHTML = res;
      };
   </script>
</body>
</html>

In the output, we can see that the filter() method filtered all the empty indices(falsy values) and returned all the truthy values.

Example: Using a While Loop

Another way to achieve the above-desired task is by using a while loop.

In the following example,

  • We have an array with some empty indices involved in it.

  • Then we created an empty array to push the values which are going to satisfy the condition in the loop.

  • Then we have a while loop and checked whether the element exists or not and pushed them into a new array.

<!DOCTYPE html>
<html>
<head>
   <title>Removing all the empty indices from array</title>
   <button onClick = "func()"> Click here! </button>
   <p id = "para"></p>
</head>
<body>
   <script>
      const array = [, , , , 4, , 6, 22, , 7, 5,77];
      document.write("Existing array : " , array);
      function func(){
         const resArr = [];
         let i = 0;
         while (i < array.length) {
            i++;
            if (array[i]) {
               resArr.push(array[i]);
            }
         };
         document.getElementById("para").innerHTML = "After removing empty indices: " + resArr;
      };
   </script>
</body>
</html>

In the output, we can see that the elements in the array which exist are pushed into a new array.

Using forEach() method

The forEach() method in JavaScript calls a function for every element in the array and this method will not execute for empty elements.

Syntax

Following is the syntax of forEach() method in JavaScript, The return value is undefined.

array.forEach(function(currentValue, index, arr), thisValue)

Parameters

  • The function parameter will iterate for every array element.

  • The currentValue, is the value of the current element in the array.

  • The index is the index of the current element.

  • arr, this parameter is the array of the current element.

Example

In this example,

  • We have an array with empty indices. By using forEach() method we’ve removed all the empty indices from array.

  • We’ve created an empty array to store the elements which are not empty. The forEach() method will iterate over the array, for each iteration it will check the current element is null or not.

  • If the element is not null, then we pushed the element into empty array.

<!DOCTYPE html>
<html>
<head>
   <title>Removing all the empty indices from array</title>
   <button onClick = "func()"> Click me! </button>
   <p id = "para"></p>
</head>
<body>
   <script>
      const array = ['apple', , , 'ball', , , , , 93];
      const ResArray = [];
      function func(){
         array.forEach(item => {
            if (item !== null) {
               ResArray.push(item);
            }
         });
         document.getElementById("para").innerHTML = ResArray;
      };
   </script>
</body>
</html>

As we can see in the output, we’ve pushed all the nonempty indices into the empty array by using the forEach() method.

Updated on: 19-Dec-2022

824 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements