How to remove elements from an array until the passed function returns true in JavaScript?


In JavaScript, there are various ways to remove elements from an array until the passed function returns true. In this tutorial, we are going to look at 3 methods in detail.

Using Array.prototype.filter()

The Array.prototype.filter() method can be used to remove elements from an array until the passed function returns true. Please refer to the Array filter() method for more details.

Example 1

The following code shows how to use this method −

<html>
<head>
   <title>Examples</title>
</head>
<body>
   <div id="array"></div>
   <div id="result"></div>
   <script>
      var arr = [1,2,3,4,5,6,7,8,9,10];
      function remove(item) {
         return item < 5;
      }
      var newArr = arr.filter(remove);
      document.getElementById("array").innerHTML = "Array: " + arr;
      document.getElementById("result").innerHTML = "Removed Elements: " + newArr;
   </script>
</body>
</html>

As you can see, we have created an array containing numbers from 1 to 10. We have then used the filter() method to remove all elements less than 5. Finally, we have displayed the new array of removed elements.

Using the for loop

Another way to remove elements from an array until the passed function returns true is to use a for loop.

Example 2

The following code shows how to use this method −

<!doctype html>
<html>
<head>
   <title>Examples</title>
</head>
<body>
   <div id="result"></div>
   <script>
      var arr = [1,2,3,4,5,6,7,8,9,10];
      var newArr = [];
      for(var i=0; i < arr.length; i++) {
         if(arr[i] < 5) {
            newArr.push(arr[i]);
         } else {
            break;
         }
      }
      document.getElementById("result").innerHTML = newArr
   </script>
</body>
</html>

As you can see, we have again created an array containing numbers from 1 to 10. We have then used a for loop to iterate through each element in the array. If the current element is less than 5, we have added it to the new array. Otherwise, we have broken out of the loop. Finally, we have displayed the new array.

Using Array.prototype.slice()

Another way to remove elements from an array until the passed function returns true is to use the Array.prototype.slice() method. Please refer to array slice method for more details.

Example 3

The following code shows how to use this method −

<!doctype html>
<html>
<head>
   <title>Examples</title>
</head>
<body>
<div id="result"></div>
<script>
     var arr = [1,2,3,4,5,6,7,8,9,10];
     var newArr = arr.slice(0,5);
     document.getElementById("result").innerHTML = newArr
</script>
</body>
</html>

As you can see, we have again created an array containing numbers from 1 to 10. We have then used the slice()method to extract the first 5 elements from the array. Finally, we have displayed the new array.

Updated on: 01-Jul-2022

355 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements