简体   繁体   English

获取分组数组的值索引

[英]Get index of value for a grouped array

I have an array of Ids我有一组Ids

 [1,1,1,2,2,2,3,3,...]

And another array of values和另一个values数组

[0,1,0,0,0,1,1,0,...]

I need to know what the zero-based index of the group of Ids is, where the corresponding value is 1 in JavaScript.我需要知道这组Ids的从零开始的索引是什么,在 JavaScript 中对应的值是1

So for this array, we might get所以对于这个数组,我们可能会得到
[1,2,0,...] because that is the index of the 1 in the Values array if you were to group the Id array by their unique values. [1,2,0,...]因为如果您要按其唯一值对 Id 数组进行分组,那么这是 Values 数组中 1 的索引。

There should only be a single 1 per group of Ids.每组 ID 应该只有一个。 There is a possibility that the group of Ids may be out of sequential order Id 组有可能乱序

(ie [1,1,2,1,2,2,3,3,...] ). (即[1,1,2,1,2,2,3,3,...] )。

But I would still want whatever the index is when the Id array is grouped.但是当 Id 数组被分组时,我仍然想要任何索引。

I tried a while loop but kept getting duplicate values.我尝试了一个 while 循环,但一直得到重复的值。 Then I tried to filter my array.然后我尝试过滤我的数组。 How can I accomplish this in JS?我怎样才能在 JS 中做到这一点?

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] . 

You could take an index counter for the same group and get the value if a value with one is found.您可以为同一组获取索引计数器,如果找到值为 1 的值,则获取该值。

Example 3:示例 3:

 [1, 2, 1, 3, 1, 1, 2, 2, 3] ids [0, 0, 1, 0, 0, 0, 1, 0, 1] values 0 0 1 0 2 3 1 2 1 indices by group ^ ^ ^ result 

 function getIndices(ids, values) { var map = new Map; return ids.reduce((r, v, i) => { if (values[i] === 1) r.push(map.get(v) || 0); map.set(v, (map.get(v) || 0) + 1); return r; }, []); } // [1, 2, 0] console.log(...getIndices([1, 1, 1, 2, 2, 2, 3, 3], [0, 1, 0, 0, 0, 1, 1, 0])); // [1, 1, 3] console.log(...getIndices([1, 1, 1, 2, 2, 2, 3, 3, 3, 3], [0, 1, 0, 0, 1, 0, 0, 0, 0, 1])); // [1, 1, 1] console.log(...getIndices([1, 2, 1, 3, 1, 1, 2, 2, 3], [0, 0, 1, 0, 0, 0, 1, 0, 1]));

Instead of a Map , you could take an object as hash table for indexing the values.您可以将对象作为哈希表而不是Map来索引值。

 function getIndices(ids, values) { var hash = Object.create(null); return ids.reduce((r, v, i) => { hash[v] = hash[v] || 0; if (values[i] === 1) r.push(hash[v]); hash[v]++; return r; }, []); } // [1, 2, 0] console.log(...getIndices([1, 1, 1, 2, 2, 2, 3, 3], [0, 1, 0, 0, 0, 1, 1, 0])); // [1, 1, 3] console.log(...getIndices([1, 1, 1, 2, 2, 2, 3, 3, 3, 3], [0, 1, 0, 0, 1, 0, 0, 0, 0, 1])); // [1, 1, 1] console.log(...getIndices([1, 2, 1, 3, 1, 1, 2, 2, 3], [0, 0, 1, 0, 0, 0, 1, 0, 1]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM