I have 2 arrays with objects
- With car brands
const brands = [
{ id: 1, name: "Mercedes Benz", bodyType: [1, 3] },
{ id: 2, name: "Audi", bodyType: [1, 2] },
{ id: 3, name: "BMW", bodyType: [3, 4] },
{ id: 4, name: "Mazda", bodyType: [1, 2, 4] }
];
- With body types
const bodyTypes = [
{ id: 1, type: "Sedan"},
{ id: 2, type: "Coupe"},
{ id: 3, type: "Hatchback"},
{ id: 4, type: "SUV"}
];
- I have picked types
const pickedTypes = [2, 4] // Coupe & SUV
How to compare this two arrays to get new array with brands that has body types that in pickedTypes
There is my try to get an array that I want
const brands = [
{ id: 1, name: "Mercedes Benz", bodyType: [1, 3] },
{ id: 2, name: "Audi", bodyType: [1, 2] },
{ id: 3, name: "BMW", bodyType: [3, 4] },
{ id: 3, name: "Mazda", bodyType: [1, 2, 4] }
];
const bodyTypes = [
{ id: 1, type: "Sedan"},
{ id: 2, type: "Coupe"},
{ id: 3, type: "Hatchback"},
{ id: 4, type: "SUV"}
];
const pickedTypes = [2, 4] // coupe & suv
let newBrandsByPickedTypes = [];
// loop for every type
for(let i = 0; i < pickedTypes.length; i++){
// loop for every brand
for(let k = 0; k < brands.length; k++){
// loop for every type in brand
brands[k].bodyType.forEach((type) => {
// if brand has type that in pickedTypes push this brand to newBrandsByPickedTypes
if(type === pickedTypes[i]){
newBrandsByPickedTypes.push(brands[k])
}
})
}
}
newBrandsByPickedTypes && console.log(newBrandsByPickedTypes); // output audi, mazda, bmw
Im stuck in this many loops actually..
It looks like it’s work but I have something like a warning: [circular object Object]]
>Solution :
You can filter from the brands array based on whether any of the ids in pickedTypes is present in individual brand’s bodyType array. Here is a possible solution
brands.filter(brand => pickedTypes.some(type => brand.bodyType.includes(type))).map(brand => brand.name)
Output
['Audi', 'BMW', 'Mazda']
In this case, since pickedType contains ids already and not names, bodyTypes array is not required, if pickedTypes had "Sedan", "Coupe" etc, you could have mapped the ids from bodyTypes and searched with that array