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) retu
Solution 1:
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];
functiondrop(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)
Post a Comment for "How To Use Break Statement In An Array Method Such As Filter?"