Home > Back-end >  Multiple filters in array
Multiple filters in array

Time:03-31

I have an object that can be null or undefined if haven't created yet. I do not have control of this object, but it returns a list of car. I'm keeping the list of cars in my cars variable:

let cars = myClass?.getCars();
/*
  cars will be an array of objects
  cars: [obj1, obj2, obj3...].
  the objects have functions:
      obj1.getRegion() => can return "North America", "Europe", "Asia", "Latin America", or "Global"
      obj1.getCarName() => returns car name. For instance, "BMW", "Lexus", "Ford"...
*/

I also have an object that returns a list of regions.

let regions = myObj?.getRegions();

Then, I want to filter my cars array to return only cars from the regions list or all cars if the variable regions contains "Global".

let cars = myClass?.getCars();
let regions = myObj.getRegions();

// check if Global region is selected 
let isGlobal = false;
regions.every(region => {
   if(region.getName() === "Global") {
      isGlobal = true;
      return true;
   }
   return false;
});

if(!isGlobal) {
  // How can I filter the cars array to return only cars from regions?
}

CodePudding user response:

For the filter you can do something like

if(!isGlobal) {
  const regionNames = regions.map( region => region.getName() )
  const filteredCars = cars.filter( car => regionNames.includes(car.getRegion()))
}

And to make it a little more error proof, if getCars or getRegions returns nothing, you can initialize those arrays at the top with something like

let cars = myClass?.getCars() ?? [];
let regions = myObj?.getRegions() ?? [];

CodePudding user response:

const myClass = null;
const cars = myClass?.getCars() ?? [];
const regions = myClass?.getRegions() ?? [];
const validRegions = regions.filter(region => region?.getName() );
const isGlobal = validRegions.some(region => region?.getName() === 'Global');
const filteredCars = isGlobal ? cars : cars.filter(car => validRegions.some(region => region?.getName() === car?.getRegion()));

Remove falsy values of region names using filter and you can compare car region and region name

  • Related