Open In App

Implement a Function that Accept Array and Condition and Returns Boolean Values in JavaScript

In JavaScript language every function is a special function that checks the element of the array with the condition given in the input, Each element is checked against the condition, and if the condition is satisfied then every function returns the true result else if any of the element of the array fails against the condition then the false result is been returned. In this article, we will see three different approaches through which we can implement the custom every function which will accept the array and the condition function and also it will return the true result if all the elements of an array satisfy the condition.

We will explore all the above approaches along with their basic implementation with the help of examples.



Approach 1: Using for loop approach

In this approach we are iterating through the array elements using the for loop in JavaScript and using the custom every function we will apply the condition function on the array elements, if the condition is satisfied then the custom every function will return true else it will return false.

Example: In this example, we will see the use of the for-loop approach.






function customEveryFunction(arrayElements, conditionFunction) {
    for (let i = 0; i < arrayElements.length; i++) {
        if (!conditionFunction(arrayElements[i])) {
            return false;
        }
    }
    return true;
}
let numbersInput = [2, 4, 6, 8, 10];
let allEvenResult = 
    customEveryFunction(
        numbersInput, num => num % 2 === 0);
console.log(allEvenResult);
  
let geekInput = 
    ["geeksforgeeks", "forgeeks", "geek"];
let allStartingWithAResult = 
    customEveryFunction(
        geekInput, word => word.startsWith("g"));
console.log(allStartingWithAResult);

Output
true
false


Approach 2: Using the Array.prototype.filter method

In this approach, we are using the inbuilt filter method in JavaScript, where the approach will compare the lengths of the input array and the array that we have as output by filtering the elements according to the condition. If the length is the same, then the true result is been returned, and the false output is been returned.

Example: In this example, we will see the use of the filter method.




function customEveryUsingFilter(arrayInput, conditionFunction) {
    return arrayInput.length === arrayInput
           .filter(conditionFunction).length;
}
  
let marksInput = 
    [85, 92, 78, 95, 55];
let allPassingOutput = 
    customEveryUsingFilter(
        marksInput, grade => grade >= 50);
console.log(allPassingOutput);
  
let AgeInput = [25, 30, 42, 16];
let allowVoting = 
    customEveryUsingFilter(
        AgeInput, age => age >= 18);
console.log(allowVoting);

Output
false
false



Article Tags :