I have an array of objects representing sales data for different cities. Each city has an array of rooms with corresponding counts. I want to check if all cities have a count of at least three for rooms 2, 3, and 4. If this condition is met, I would like to obtain the names of all the cities that satisfy it.
Here is an example of the data structure:
const sales = {
"City 1": [
{
"rooms": 1,
"count": 1
},
{
"rooms": 2,
"count": 2
},
{
"rooms": 3,
"count": 3
}
],
"City 2": [
{
"rooms": 1,
"count": 1
},
{
"rooms": 2,
"count": 1
},
{
"rooms": 3,
"count": 1
},
{
"rooms": 4,
"count": 2
}
],
"City 3": [
{
"rooms": 2,
"count": 6
},
{
"rooms": 4,
"count": 7
}
],
"City 4": [
{
"rooms": 1,
"count": 4
},
{
"rooms": 2,
"count": 6
},
{
"rooms": 3,
"count": 3
},
{
"rooms": 4,
"count": 7
}
]
};
Several solutions I tried
for (const city in sales) {
let isPass = true;
for (const room of sales[city]) {
if (room.count < x) {
isPass = false;
break;
}
}
if (isPass) {
// do stuff here
return true;
}
}
Also tried
let filteredCities = [];
for (const city in sales) {
const roomsData = sales[city];
const hasRoom2 = roomsData.some((room) => room.rooms === 2);
const hasRoom3 = roomsData.some((room) => room.rooms === 3);
const hasRoom4 = roomsData.some((room) => room.rooms === 4);
const isCount = roomsData.every(
(room) => room.count >= 3
);
if (hasRoom2 && hasRoom3 && hasRoom4 && isCount) {
filteredCities.push(city);
}
}
return filteredCities;
I need assistance in writing a JavaScript function that will perform this check and return the following:
A boolean value indicates whether all cities have at least three counts for rooms 2, 3, and 4.
If the boolean value is true, a list of the names of the cities that satisfy the condition.
2
Answers
So when you’re checking each city, you just need to keep track of records that meet the requirements. You can do this by using a Set filled with relevant
rooms
numbers. As you loop through the records, for each record, check ifrooms
is both present in the set and satisfies the condition. If true, delete it from the set. When the set becomes empty, you are sure that the current city passed the test. Refill the set for each subsequent city and repeat.