Search code examples
javascriptarraysalgorithmarray-algorithms

Impementing drop it function in javascript but the require answer didn't get it


Intermediate Algorithm Scripting: Drop it

Given the array arr, iterate through and remove each element starting from the first element (the 0 index) until the function func returns true when the iterated element is passed through it.

Then return the rest of the array once the condition is satisfied, otherwise, arr should be returned as an empty array.

function dropElements(arr, func) {
  let newArr=[];
  for(let i=0; i<arr.length; i++){
    if(func(arr[i])){
      newArr.push(arr[i])
    }
  }
  return newArr;
}

console.log(dropElements([0, 1, 0, 1], function(n) {return n === 1;}));
console.log(dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;}));
  • I get an output of a first test is: [1, 1] and
  • the second test get: [ 3, 9 ] but the required output should be: [1,0,1] and [3, 9, 2];

Solution

  • There is also a fairly elegant recursive solution to this. It's probably not very time- or space-efficient one, but it is simple and clear:

    const dropElements = (xs, fn) => 
      xs .length == 0
        ? []
      : fn (xs [0]) 
        ? xs 
      : dropElements (xs .slice (1), fn)
    
    console.log(dropElements([0, 1, 0, 1], function(n) {
      return n === 1;
    }));
    console.log(dropElements([1, 2, 3, 9, 2], function(n) {
      return n > 2;
    }));

    Passed an array and a function, if the function returns true for the first element, we return the entire array. If not, we drop the first element (.slice (1)) and try again, stopping when the array is empty.