Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use break statement in an Array method such as filter?

I was trying to solve an algorithm challenge which required;

Drop the elements of an array (first argument), starting from the front, until the predicate (second argument) returns true.

The second argument, func, is a function you'll use to test the first elements of the array to decide if you should drop it or not.

Return the rest of the array, otherwise return an empty array.

Though I have been able to come up with a lengthy solution to this through looping the array I was wondering if there is a way to implement the break statement inside the methods.

Could it be accomplish by redefining the Array.prototype.filter method to accept a break statement ?

Though the solution could have been easy as such the methods of arrays in JavaScript doesn't accept this. How do you bypass that?

function dropElements(arr, func) {
  return arr.filter(func);
}
like image 689
Ozan Avatar asked Mar 09 '23 09:03

Ozan


1 Answers

You can just use for loop and when function returns true you can just break loop and return results from that index.

var arr = [1, 2, 3, 4, 5, 6, 7, 8];

function drop(data, func) {
  var result = [];
  for (var i = 0; i < data.length; i++) {
    var check = func(data[i]);
    if (check) {
      result = data.slice(i);
      break;
    }
  }
  return result;
}

var result = drop(arr, e => e == 4)

console.log(result)

You can also use findIndex() and if match is found you can slice array from that index otherwise return empty array.

var arr = [1, 2, 3 ,4 ,5 ,6 ,7, 8];

var index = arr.findIndex(e => e == 4)
var result = index != -1 ? arr.slice(index) : []

console.log(result)
like image 109
Nenad Vracar Avatar answered Mar 12 '23 02:03

Nenad Vracar