+ 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.
6 Respuestas
+ 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
}
+ 4
Array.prototype.find()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
+ 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?
+ 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]
+ 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;
} ));