-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdropIt.js
33 lines (24 loc) · 1.08 KB
/
dropIt.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/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) {
const index = arr.findIndex(func)
if (index === -1) {
return []
}
if (index === 0) {
return arr
}
return arr.splice(index, arr.length - 1)
}
dropElements([1, 2, 3, 4], function(n) { return n >= 3; }) // [3, 4]
dropElements([0, 1, 0, 1], function(n) { return n === 1; }) // [1, 0, 1]
dropElements([1, 2, 3], function(n) { return n > 0; }) // [1, 2, 3]
dropElements([1, 2, 3, 4], function(n) { return n > 5; }) // []
dropElements([1, 2, 3, 7, 4], function(n) { return n > 3; }) // [7, 4]
dropElements([1, 2, 3, 9, 2], function(n) { return n > 2; }) // [3, 9, 2]