1

I have 2 array:

var arr1 = [1, 1, 2, 3, 4, 4];
var arr2 = [];

arr1 defines some groups, the group members are defined by the position. So the group members 0 and 1 belong to group 1,
member 2 belong to group 2,
member 3 belong to group 3,
the group member 4 and 5 belong to group 4.

I would like to load the groups with their members into another array, so that I looks like:

arr2 = [[0,1], [2], [3], [4,5]];

So group 1 has the members 0 and 1 and so on...

When doing:

for(i=0; i<arr1.length; i++){
    arr2[arr1[i]] = i;
}

I get:

arr2 = [1: 1, 2: 2, 3: 3, 4: 5];
Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181

3 Answers3

2

You've almost gotten it right, but you need to create an array for each index in arr2, and then append i to it:

for(i=0; i<arr1.length; i++){
    arr2[arr1[i]] = arr2[arr1[i]] || [];  // create array here if none exists yet
    arr2[arr1[i]].push(i)                 // add i to array
}

Note that this produces an of-by-one difference from your desired solution (the first group will be at index 1, rather than index 0 in your solution), so you can shift the indicies of arr2 down by one:

for(i=0; i<arr1.length; i++){
    arr2[arr1[i]-1] = arr2[arr1[i]-1] || [];
    arr2[arr1[i]-1].push(i)
}

Note that you have not specified your desired behavior if there would be a gap in the arr2 result. In this case, the index remains unset in the output array.

apsillers
  • 112,806
  • 17
  • 235
  • 239
  • What does `||` mean in this context? – Evgenij Reznik Mar 10 '16 at 20:46
  • @user1170330 [What does β€œvar FOO = FOO || {}” mean in Javascript?](http://stackoverflow.com/questions/6439579/what-does-var-foo-foo-mean-in-javascript) -- if the left side is "falsey" (`undefined`, `null`, empty string, `0`), then the expression evaluates to the right side -- in this case, a new empty array. Otherwise, it evaluates to the left side. So, it means "set `arr2[arr1[i]]` to itself, unless it doesn't have a value, in which case set it to an array" – apsillers Mar 10 '16 at 20:47
1

You need to create new array for each group and then push values to it. See my comments in code below:

var arr1 = [1, 1, 2, 3, 4, 4];
var arr2 = [];

for(i=0; i<arr1.length; i++) {
    // array indexes begins from 0, therefore arr2[arr1[i] - 1]
    if (!arr2[arr1[i] - 1]) { // if array for this index does not exist
        // then initialize new empty array
        arr2[arr1[i] - 1] = [];
    }
    arr2[arr1[i] - 1].push(i); // push correct value to the array
}
madox2
  • 49,493
  • 17
  • 99
  • 99
1
var i;  
var arr2 = [];
for(i=0; i<arr1.length; i++){
  arr2[arr1[i]-1] = arr2[arr1[i]-1] || [];
  arr2[arr1[i]-1].push(i);
}
Jerome WAGNER
  • 21,986
  • 8
  • 62
  • 77