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.
Method 1: JavaScript slice() Method
In a function, if there are multiple return statements only the first return statement gets executed and the function gets completed.
Code Snippet:
var retrieveRemoved = function (arg_1, arg_2) { var i; for (i = 0; i < array.length; i++) { if (condition) { return statement1; } } return statement2; }
Example: In this example, we will be using the slice() method to get removed elements of a given array until the passed function returns true in JavaScript
Javascript
<script> var array = [1, 2, 2, 3, 4, 5, 6, 6, 7, 8, 8, 8]; // Removing elements less than 5 and returning them var limiter = 5; // function which slices the array taking limiter as parameter var retrieveRemoved = function (array, limiter) { var i; for (i = 0; i < array.length; i++) { // If the number value is greater or equal than limiter if (array[i] >= limiter) { // It takes the array from 0th // index to i, excluding it return array.slice(0, i); } } return array.slice(i); } var removed = retrieveRemoved(array, limiter); console.log( "The removed elements: " + removed); </script> |
Output:
The removed elements: 1,2,2,3,4
Method 2: 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.
Example: In this example, we will be using another array to get removed elements of a given array until the passed function returns true in JavaScript
Javascript
<script> var array = [1, 2, 2, 3, 4, 5, 6, 6, 7, 8, 8, 8]; // Removing elements less than 5 and returning them var limiter = 5; var retrieveRemoved = function (array, limiter) { var i,s; var res=[]; for (i = 0; i < array.length; i++) { if (array[i] < limiter) { // Push() method is used to // values into the res[]. res.push(array[i]); } else { s=i; break ; } } return res; return array.slice(i); } var removed = retrieveRemoved(array, limiter); console.log( "The removed elements are: " + removed); </script> |
Output:
The removed elements are: 1,2,2,3,4
Please Login to comment...