Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether array has a number bigger than specified

I want to write a function that takes array as an argument and returns how many numbers can be divided by 12. However, if array has a number higher than 111 then it should return 0; I wrote this:

function isDivisble(array) {
  let numberOfNum = 0;
  for(let i=0; i < array.length; i++) {
    if(array[i] % 12 == 0 && array[i] < 111) {
      numberOfNum = numberOfNum + 1 ;
    } else {
      numberofNum = 0;
    }
  }
  return console.log(numberOfNum);
}

let test = [12, 24, 36, 44, 55, 255];


isDivisble(test)

I realized that this code checks individually whether the current number is divisible and not higher than 111 and not globally whether the array has a number higher than 111, but I dont understand how to make a general array check. Is writing for loop with if statement to check and then another for loop inside if statement makes it a little bit spaghetti?

like image 532
Maivan Fildero Avatar asked Aug 15 '21 12:08

Maivan Fildero


1 Answers

You can use some to check if there is any element which is greater than 111 first. Then you can use filter to get element that is divisible by 12. Like this:

const isDivisible = (arr) => {
    if (arr.some((e) => e > 111)) return 0;
    return arr.filter((e) => e % 12 === 0).length;
};
const test = [12, 24, 36, 44, 55, 48];
console.log(isDivisible(test));
like image 71
Trung Hieu Nguyen Avatar answered Oct 03 '22 06:10

Trung Hieu Nguyen