Reputation: 699
I have an array of houses which has an array of rooms inside.
Each room, house, and street has a unique ID (eg: If rooms in house 1, have ID 1..4, rooms in house 2 will have ID 5..9)
var street = {
id = 1,
streetname = 'stack street',
houses = [
{
id: 1,
type: 'brick'
rooms: [
{
id: 1,
color: 'blue'
}, ... a bunch more
]
}, ... a bunch more
]
}
Are there easy solutions like arr.findIndex()
for:
Upvotes: 1
Views: 2589
Reputation: 9650
1) The findIndex()
is that easy solution but you need to employ an array function once more to scan through rooms within the house check callback:
var houseIndex = street.houses.findIndex(h => h.rooms.some(r => r.id === roomId));
2) Just the same with find()
:
var house = street.houses.find(h => h.rooms.some(r => r.id === roomId));
or if the earlier index lookup is in place, use its result:
var house = street.houses[houseIndex];
3) Flatten the house-room hierarchy into a plain room list and search it for the desired room:
var room = street.houses.flatMap(h => h.rooms).find(r => r.id === roomId);
Upvotes: 3
Reputation: 699
For room id 7:
1)
int houseIndex = street.houses.findIndex(house => house.rooms.find(room => room.id == 7));
int roomIndex = street.houses.find(house => house.rooms.find(room => room.id == 7)).rooms.findIndex(room => room.id == 7)
2)
var houseObject = street.houses.find(house => house.rooms.find(room => room.id == 7))
3)
var roomObject = street.houses.find(house => house.rooms.find(room => room.id == 7)).rooms.find(room => room.id == 7)
Upvotes: 0