Find element in array that complies to multiple conditions


How do I find the first boiler that responds to the following conditions:
h_cap >= req_h_cap AND
ww_cap >= req_ww_cap

const boilers = [
{CW:1, ww_cap: 0, h_cap: 12, boiler_costs: 2200},
{CW:2, ww_cap: 0, h_cap: 15, boiler_costs: 2400},
{CW:3, ww_cap: 18, h_cap: 20, boiler_costs: 2600},
{CW:4, ww_cap: 22, h_cap: 24, boiler_costs: 2800},
{CW:5, ww_cap: 28, h_cap: 32, boiler_costs: 3000},
{CW:6, ww_cap: 38, h_cap: 32, boiler_costs: 3200},
] ;

Kind regards and many thanks

Assuming the req_ should be some kind of value coming from users choice

const matchList = boilers.Filter( b => b.h_cap > req_h_cap &6 b.ww_cap > req_ww_cap);
    return matchList[0];

Thanks Thallius!

How would you change the formula, if you are only interested in the CW value of the first boiler in the array that matches both conditions?

Kind regards

Here is how I would find them. With your array of boilers, I would also have an array of conditions.

const conditions = [
  (boiler, requirements) => boiler.ww_cap >= requirements.req_ww_cap,
  (boiler, requirements) => boiler.h_cap >= requirements.req_h_cap,

Then I would check for the first boiler that matches all of the conditions.

  const found = boilers.find(function (boiler) {
    return conditions.every(function (condition) {
      return condition(boiler, requirements);

You can see some example code of that at

Or, if you want to use arrow notation:

  const found = boilers.find(
    (boiler) => conditions.every(
      (condition) => condition(boiler, requirements)
1 Like

To be honest for me this is an example where the new way of „clean code“ is going a step too far.

I find your code much harder to read then just using a and condition in the find itself

const found = boilers.find(
    (boiler) => boiler.ww_cap >= requirements.req_ww_cap && 
                boiler.h_cap >= requirements.req_h_cap
1 Like

I agree, using the conditions directly inline does result in easier to understand code.
I am guilty of premature optimisation.

Later on if a wider range of conditions were needed, or if the number of requirements were wanting to be changed, then extracting them out to an array would be appropriate.


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.