Home > database >  Create a function that, given an array and declared a variable, returns true or false if the variabl
Create a function that, given an array and declared a variable, returns true or false if the variabl

Time:11-25

I would like to create a program from a function that, given an array made up of a series of numbers and declared a variable with a value, returns true if the value exceeds each of the numbers in array and otherwise returns false.

let array = [5000, 5000, 3]
let value = 2300;


function compare_Values(table,number){
    
    
  for(let i = 0; i <= table.length; i  ){
    
      if(number < table[i]){
        
        var result = "FALSE: failed ";

      } else{
       var result = "TRUE: if passed";
    }
          return result
  }
}



console.log(compare_Values(array,value))

I don't know why the result returns FALSE. The value does not exceed each of the elements in the table. Can someone help me? I don't know where is my mistake.

CodePudding user response:

If I understood it correctly, then there are lots of ways to solve this problem, but I'll show you 2 of them.

By using a common for loop -- you just initialize a result (res) outsite the for loop and then stops the iteration if any element is lower than the n

function solve(arr, n) {
    let res = true;
    for (let i = 0; i < arr.length && res; i  ) {
        res = n <= arr[i];
    }

    return res;
}

By using the Array.prototype.every() method:

let arr = [5000, 5000, 4000];
let n = 2300;

console.log(arr.every(v => n <= v));

CodePudding user response:

You should put return outside the for loop

let array = [5000, 5000, 3]
let value = 2300;


function compare_Values(table,number){
  var result;  
  for(let i = 0; i < table.length; i  ){    
      if(number < table[i]){        
        result = "TRUE: if passed";
      } else{
       result = "FALSE: failed";
       return result;
    }
  }
  return result
}



console.log(compare_Values(array,value))
  • Related