How to use for() Loop In Javascript

In this method, we will take the removed element using the for loop. We can apply the comparator function and get the removed value till the condition gets true.

Example:

Javascript
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let removeArr = [];
for (let i = 0; i < arr.length; i++) {
    if (arr[i] < 6) {
        removeArr.push(arr.shift());
    } else {
        break;
    }
}
console.log(removeArr);

Output
[ 1, 2, 3 ]


How to get removed elements of a given array until the passed function returns true in JavaScript ?

The arrays in JavaScript have many methods which make many operations easy. 

In this article let us see different ways how to get the removed elements before the passed function returns something. Let us take a sorted array and the task is to remove all the elements less than the limiter value passed to the function, we need to print all the removed elements.

These are the following ways by which we get the removed elements of a given array:

Table of Content

  • Using for() Loop
  • Using slice() Method
  • Using another array
  • Using array.filter() Method
  • Using Array.splice()

Similar Reads

Using for() Loop

In this method, we will take the removed element using the for loop. We can apply the comparator function and get the removed value till the condition gets true....

Using slice() Method

In a function, if there are multiple return statements only the first return statement gets executed and the function gets completed....

Using another array

Another array can be used to check the condition. If it does not satisfy the condition, these are the elements to be removed.  We push all the elements that don’t satisfy the condition into another array and return the resultant array....

Using array.filter() Method

The JavaScript Array filter() Method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method....

Using Array.splice()

In this approach, we utilize the splice() method to remove elements from the array based on the condition until the passed function returns true. The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place....