Search code examples
javascriptarraysstatic-linking

Linking 2 javascript arrays


I have 2 arrays of objects: users and channels. Each user can be in many channels. Each channel can contain many users.

Channel object example:

{name: "test", visible: true, active: true}

User object example:

{name: "user", ip: '127.0.0.1', sex: 1}

Script must do such actions:

  1. Display users list by channel.
  2. Display channels list by user.
  3. All basic actions (add/remove/update user/channel);

What will be the better way to implement linking between these objects:

  1. User will contain his channels list.
  2. Channel will contain his users list.
  3. Create separate object which will contain user=channel assosiations.
  4. Or your variant...

I think that third variant will be better.


Solution

  • As you are aware, there are many ways to do this and which way ultimately depends more on how you're going to use, access and store the data than you have disclosed to us. But, here's one way that could work:

    Create an object for a user:

    function user(name, id, ip, sex, channels) {
        this.name = name;
        this.id = id;
        this.channels = channels || [];
        this.ip = ip;
        this.sex = sex;
    
        this.addChannel = function(channel) {
            this.channels.push(channel);
        }
    }
    

    Then, you can have an array of user objects, where each user object contains the basic information about the user and contains the list of channels. This data structure choice optimized for being able to easily know which channels a user belongs to.

    This structure does not optimize for knowing which users are in a given channel. If you wanted that information from this data structure, you could still calculate it, but it would involve looking in every user object to find out which users were in a given channel. It's doable, but not fast.

    If you need both types of information (which channels a user is in and which users are in a channel) available fast, then you may need to double maintain two data structures, one that gives you each answer. If you do all manipulation of the channels via methods or helper functions, then they can both be maintained automatically.

    The choice ultimately depends upon how you most need to access the data and which types of access must be fast. Since you haven't shared that info, we can't really say which would be better.