1

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:

  1. Given a room ID, return the index of the house in the array houses, and the index of the room in the array rooms of that house
  2. Given a room ID, return the house it's in
  3. Given a room ID, return the room object
1

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.