Given an array (myArray), write a JS program to find the index of the first boolean value in myArray using "findIndex()" method. Note: If the value is not present in the array, findIndex() returns "-1".Input :The first line of input will contain an array (myArray).Output:
The output should be a single line containing the index or -1.
input1:[ 'a', true, 'v', 5 ]
output1:1
// input array
const myArray = [ 'a', true, 'v', 5 ];
// function findIndex()
function findIndex(myArray) {
// variables with max values
var t = Number.MAX_VALUE;
var f = Number.MAX_VALUE;
// conditions to check if there is a boolean value or not.
// if yes, then respective variable will be assigned the first index of the value.
if(myArray.includes(true)){
t = myArray.indexOf(true);
}
if(myArray.includes(false)){
f = myArray.indexOf(false);
}
// if there is no boolean value then both variables will be set to -1
if(!myArray.includes(false)&& !myArray.includes(true)){
t = -1;
f= -1;
}
// return conditions for what comes first.
if(t>f){
return f;
}
else{
return t;
}
}
// implementing the function
console.log(findIndex(myArray));
For input1:[ 'a', true, 'v', 5 ]
Comments
Leave a comment