Home > Article > Web Front-end > 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 will go over 3 methods in detail.
The Array.prototype.filter() method can be used to remove elements from an array until the passed function returns true. See the Array filter() method for more details.
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. Then use the filter() method to remove all elements less than 5. Finally, we show the new array with the deleted elements.
Another way to remove elements from an array until the passed function returns true is to use a for loop.
Example 2The 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 a array. We then use a for loop to iterate over each element in the array. If the current element is less than 5, we add it to the new array. Otherwise, we are out of the loop. Finally, we display the new array.
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 the array slicing method for details.
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 a array. We then use the slice() method to extract the first 5 elements from the array. Finally, we display the new array.
The above is the detailed content of How to remove elements from an array until the passed function returns true in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!