How can I create an object from two separate lists with repeated items in the key list?

Options

Hi all,

I have the following two arrays:

[0,0,1,0,0,1,0] and [a,b,c,d,e,f]

and I would want the following object:

{0:[a,b,d,f],1:[c,e]}

That is, I want items in the first array to become the keys (0 and 1) and corresponding items in the other array to become the values. Repeated Items in the key array are will have the corresponding items in the values array placed in an list.

I have tried within my abilities and I keep getting the following

{0:a,1:c}.

Your help would be highly appreciated. Thanks.

Tagged:

Answers

  • Chris Coleman
    Chris Coleman Administrator

    ADMIN

    Options

    Hi there! I realize this is quite an old post, but I stumbled upon it and wanted to provide a potential solution just in case anyone else will find this useful. This is definitely a tricky one as most existing solutions require the data to be sequential in the sense that we could end up with a: 0, b: 0, c: 1, etc… I notice that your first array has more entries than your second. For the sake of building a workable example, I'm going to assume that this was in error (please correct me if I'm wrong). I think we can utilize the For Loop for this.

    Let's say we have two arrays that are both 5 entries in length.

    [1, 2, 1, 1, 2]

    [a, b, c, d, e]

    and I want to end up with:

    {1: [a, c, d}, 2: [b, e]}

    A note to start; we can't use numbers as the names of our keys, so these will end up as text. We also can't use 0, which is why I used 1 and 2 instead.

    We need to take the keys array, and pull the unique values out of it. You'll then loop against the unique values to construct the object that holds our result.

    Then, for each of our original entries in our Keys array, we'll use the current iteration of a new loop to determine which value to grab, and update the original array that matches that key using the Push filter.

    It's not very complex, but there are several steps, so I've outlined in a screenshot below and created a snippet so you can import it into your workspace and follow along a little more closely. Let me know if I can clarify anything here.

  • Alimama
    Alimama Member
    Options

    hi @Chris Coleman. I just saw this. I haven't been checking my profile here. This is great! Many many thanks for this, it is still very useful. I will now return to my original problem and get it solved.

  • Alimama
    Alimama Member
    Options

    Hi @Chris Coleman it would be great to gain more insight from your snippet but it seems incomplete compared to the solution in the image above in your response.