Non
Non

Reputation: 8589

How can I call filter once when I need to filter multiple things at the same time?

I am using lodash to perform some filtering.

I have this functions:

filterByCardinalPoint = (key, value) => {
    const { passengersData } = this.props;
    console.log('passengersData', passengersData);
    return filter(passengersData, [key, value]);
  };

  callFilter = () => {
    passengersGoingNorth = this.filterByCardinalPoint('cardinalpoint', 'N')
      .length;
    passengersGoingSouth = this.filterByCardinalPoint('cardinalpoint', 'S')
      .length;
    passengersGoingWest = this.filterByCardinalPoint('cardinalpoint', 'W')
      .length;
    passengersGoingEast = this.filterByCardinalPoint('cardinalpoint', 'E')
      .length;
  };

And I am calling callFilter in the render method. This function is called around 8 times. How can I optimize it so that is call once?

Upvotes: 0

Views: 49

Answers (2)

Ori Drori
Ori Drori

Reputation: 192287

Since you need the amount of people going in each direction, you can use _.countBy() with _.property() as the iteratee. Destructure the result object to assign the numbers to the variables.

Example:

const { countBy, property } = _;

let passengersGoingNorth, passengersGoingSouth, passengersGoingWest, passengersGoingEast;

const passengersData = [{ cardinalpoint: 'N' }, { cardinalpoint: 'N' }, { cardinalpoint: 'S' }, { cardinalpoint: 'N' }, { cardinalpoint: 'E' }];

({
  N: passengersGoingNorth = 0,
  S: passengersGoingSouth = 0,
  W: passengersGoingWest = 0,
  E: passengersGoingEast = 0
} = countBy(passengersData, property('cardinalpoint')));

console.log(passengersGoingNorth, passengersGoingSouth, passengersGoingWest, passengersGoingEast); // 3, 1, 0, 1
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Upvotes: 2

Jonas Wilms
Jonas Wilms

Reputation: 138427

Maybe thats too oldschool, but what about a simple for loop:

 for(const { cardinalpoint } of passengersData) {
   if(cardinalpoint === "N")
    passengersGoingNorth++;
   if(cardinalpoint === "S")
    passengersGoingSouth++;
   if(cardinalpoint === "E")
    passengersGoingEast++;
   if(cardinalpoint === "W")
    passengersGoingWest++;
 }

If that is too repetitive, just use the direction as a lookup key:

 const directions = { N: 0, S: 0, W: 0, E: 0 };
 for(const passenger of passengersData)
   directions[ passenger.cardinalpoint ]++;

Then you can get the passengers going south as directions.S.

Upvotes: 1

Related Questions