Create a function that, given an array and declared a variable, returns true or false if the variable exceeds each element of the array

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 = "TRUE: if passed";

      } else{
       var result = "FALSE: failed";
    }
          return result
  }
}



console.log(compare_Values(array,value))

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

>Solution :

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));

Leave a Reply