0

I have an array of users of type User = { id: number; name: string; floor: number }, where floor: number is a floor in the company where given user is working. I want to create an array building of N floors (number is constant), and every building[i] must contain a list of users (an array of User).

So it should look like this:

building = [
    1: [ [11, bob, 1], [42, jane, 1], [33, tom, 1] ],
    2: [ [14, amir, 2], [35, isaac, 2] ],
    ...
    N: [ [62, jack, N], [93, tobby, N], [21, elisa, N] ],
]

I try to implement idea in the next code:

type User = { id: number; name: string; floor: number }
building: Array<User[]>;
foo() {
    this.building = new Array<User[]>(3);
    ...
    for (let i = 0; i < users.length; i++) {
        if ( users[i].floor ) {
            this.building[users[i].floor].push(users[i]);
        }
    }
}

But when I run code there is an error: core.mjs:6485 ERROR TypeError: Cannot read property 'push' of undefined

What I missing?

2
  • 2
    you are not initializing your inner array you are just declaring something. Commented Jun 27, 2022 at 16:09
  • 2
    this.building = new Array<User[]>(3); does not create an array with three User[] arrays in it. It creates an array with three empty slots in it. Commented Jun 27, 2022 at 16:09

1 Answer 1

1

You have to initialize the arrays within the first array before you can push elements, like this:

class MyClass {
    type User = { id: number; name: string; floor: number }
    building: Array<User[]>;

    foo() {
        this.building = new Array<User[]>(3);
        // ...
        for (let i = 0; i < users.length; i++) {
            if (users[i].floor) {

                // Create the array if not already existing
                this.building[users[i].floor] ||= [];
                this.building[users[i].floor].push(users[i]);
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

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.