Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading