In my JavaScript code, I am dealing with two arrays. One array contains Ids
:
[1,1,1,2,2,2,3,3,...]
The other array holds values
:
[0,1,0,0,0,1,1,0,...]
What I need to do is determine the zero-based index of the group of Ids
where the corresponding value is 1
.
For example, for these arrays, the result could be:
[1,2,0,...]
This means that it is the index of the 1 in the Values array when grouped by the unique values in the Id array.
Keep in mind that there should only be a single 1 per group of Ids, even if the groups are not in sequential order like:
[1,1,2,1,2,2,3,3,...]
. In this case, I still want the correct index for the grouped Ids.
I initially tried using a while loop but encountered duplicate values. Then I attempted to filter my array without complete success. Is there a way to achieve this task in JavaScript?
Examples:
Array 1 (IDs): [1,1,1,2,2,2,3,3,3,3]
Array 2 (Values): [0,1,0,0,1,0,0,0,0,1]
Result Array: [1,1,3]
Array 3 (IDs): [1,2,1,3,1,1,2,2,3]
Array 4 (Values): [0,0,1,0,0,0,1,0,1]
Result Array: [1,1,1]