Friedpanseller
Friedpanseller

Reputation: 699

Find index of object by id in array of arrays

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

Upvotes: 1

Views: 2589

Answers (2)

Dmitry Egorov
Dmitry Egorov

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

Friedpanseller
Friedpanseller

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

Related Questions