Answer to Question #241758 in HTML/JavaScript Web Application for rasi

Question #241758

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


1
Expert's answer
2021-09-25T03:03:49-0400
// 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 ]

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS