Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
Using Array.prototype.every or Array.property.some depending on condition

I'm trying to make a function to filter some data using OR/AND logical operator depending on what the user selects. That means I need to use Array.prototype.every (AND) or Array.property,some (OR) to fullfill my requirement.

To avoid code redundancy I was trying to do something like this:

const functionApplied = condition === 'ALL'
        ? myArray.every
        : myArray.some;

functionApplied(item =>  {
    ... aux code ...
})
functionApplied.call(item =>  {
    ... aux code ...
})

Is there an analogous way to do it like this?

I know I could do something like this, but I'm just curious about above sintax...

const auxFunction = (item) => {...};
if (condition === 'ALL') {
    myArray.every(item => auxFunction(item));
} else {
    myArray.some(item => auxFunction(item));
}

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can definitely do something similar to what you're hoping to achieve. Here's one way:

function checkCondition(condition, booleanFunc, myArray) {
    const functionApplied = condition === 'ALL'
        ? myArray.every.bind(myArray)
        : myArray.some.bind(myArray);

    return functionApplied(booleanFunc);
}

console.log(checkCondition('ANY', (item) => {return item > 2}, [1,4,5,6]));
console.log(checkCondition('ANY', (item) => {return item > 2}, [4,5,6]));
console.log(checkCondition('ANY', (item) => {return item > 2}, [1,2]));
console.log(checkCondition('ALL', (item) => {return item > 2}, [1,4,5,6]));
console.log(checkCondition('ALL', (item) => {return item > 2}, [4,5,6]));

VLAZ comment is another good direction.

about 4 years ago · Juan Pablo Isaza Report

0

You can use a variable holding the property name, and then use dynamic property access.

function functionApplied(condition) {
  return functionApplied === 'ALL' ? 'every' : 'some';
}

let result = myArray[functionApplied(condition)](item => { ... });

about 4 years ago · Juan Pablo Isaza Report

0

Yep, VLAZ comment is the way I wanted, this works:

const functionApplied = condition === 'ALL'
        ? Array.prototype.every
        : Array.prototype.some;

functionApplied.call(myArray, item =>  {
    ... aux code 

Thanks everyone for your quick answers :)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!