+ 1

Which array method is suitable for returning the first elements that evaluate to true?

Incase an encountered element is false, the loop should break. The function should omly return the first ones that passed.

9th Jul 2020, 8:43 AM
asɥɐ🔹ʞɐɹnnƃı
asɥɐ🔹ʞɐɹnnƃı - avatar
6 Antworten
+ 6
This? let arr = [true, true, false, true]; console.log(arr.slice(0,arr.indexOf(false))) Or this? let arr = [true, 1, 0, false, true]; console.log(arr.slice(0,arr.findIndex(isFalse))) function isFalse(x) { return Boolean(x) === false }
9th Jul 2020, 9:01 AM
Russ
Russ - avatar
+ 4
The first elements? You mean display all the truthy ones and stop on finding the first falsey one? "The function should only return the first ones that passed." Incomplete here, passed what?
9th Jul 2020, 8:58 AM
Ipang
+ 4
Ipang exactly...it should stop on the falsey! eg arr = [1,1,1,0,0] If arr [i]==1, the first three pass and so should stop going through the array at arr [3]
9th Jul 2020, 9:24 AM
asɥɐ🔹ʞɐɹnnƃı
asɥɐ🔹ʞɐɹnnƃı - avatar
+ 4
asɥɐ🔹ʞɐɹnnƃı🇺🇬 Not too sure here, but maybe Array::some method be kinda related. Reference: https://www.w3schools.com/jsref/jsref_some.asp Example to print the index of the first falsey of array <arr> arr = [ true, true, true, true, false, true ]; console.log(arr.some( ( value, index ) => { if(!value) console.log(index) // index of falsey element return !value; } ));
9th Jul 2020, 10:14 AM
Ipang
+ 3
Thanks Russ, Ipang & Gordon
9th Jul 2020, 2:46 PM
asɥɐ🔹ʞɐɹnnƃı
asɥɐ🔹ʞɐɹnnƃı - avatar