I have a mental block that does not allow me to move forward.
I have an array that I will exemplify with the following code:
let cars = [
{ brand: "Ford", year: "2012", color: "White", doors: "5", model: "One" },
{ brand: "Chevrolet", year: "2021", color: "Red", doors: "5", model: "Two" },
{ brand: "Chevrolet", year: "2000", color: "Black", doors: "5", model: "Three" },
{ brand: "Citroen", year: "2004", color: "Pink", doors: "3", model: "Four" },
];
I need to store in a variable all those cars that meet the condition of having 5 doors. Well,
let carsWithFiveDoors = cars.filter(({ doors }) => doors == "5");
But I also need it to meet two conditions at the same time. To be more clear, to my new array that has only those 5-door cars, I need to apply another filter that allows me to have only those cars that are not Chevrolet branded, nor red. The problem arises when, by simple logic, I apply this method to my array:
carsWithFiveDoors.filter(({ brand, color }) => brand !== "Chevrolet" && color !== "Red");
The result of this filter is the following array:
let newArrayOfCars = [
{
brand: "Ford",
year: "2012",
color: "White",
doors: "5",
model: "One",
},
{
brand: "Toyota",
year: "2000",
color: "Black",
doors: "5",
model: "Three",
},
{
brand: "Citroen",
year: "2004",
color: "Pink",
doors: "3",
model: "Four",
},
];
With that method what I achieved was to generate an array without any Chevrolet vehicles, but I need to filter out those cars that, at the same time, are red and Chevrolet branded.
How could I achieve this? I’ve given it a lot of thought and I think I’ve already burned out.
>Solution :
Since you need to filter out cars that are both brand Chevrolet and red, you need to implement the following logical expression:
let newArrayOfCars = carsWithFiveDoors.filter(({ brand, color }) => !(brand === "Chevrolet" && color === "Red"));