简体   繁体   English

当索引满足其他条件时,查找Javascript数组元素的值和索引

[英]Find value and index of Javascript array element when the index meets another condition

I have two arrays: 我有两个数组:

arr1 = [0,1,1,0]
arr2 = [a,b,c,d]

I would like to find the values and corresponding indices of arr2[ i ] where i is such that arr1[ i ] != 0 without looping through each position in arr2. 我想找到arr2 [i]的值和相应的索引,其中i使得arr1 [i]!= 0而不循环遍历arr2中的每个位置。 What efficient techniques could do something like the following: 什么有效的技术可以完成以下任务:

arr2.forEach( ( 'element with index such that arr1[index] != 0') => {} );

** EDIT ** The initial posting of this question wasn't clear about needing to record the indices of the elements that met the condition. **编辑**这个问题的最初发布尚不清楚是否需要记录满足条件的元素的索引。

EDIT: getting the indices too is easy - updated the answer 编辑:获取索引也很容易-更新了答案

You say you don't want to loop through arr2 but what you could do is loop through arr1 and collect the respective value of arr2 everytime you get a hit like so: 您说您不想循环遍历arr2,但是您可以做的是遍历arr1并在每次命中时收集arr2各自的值,如下所示:

let result = []
arr1.forEach((value, idx) => {
    if (value !== 0) result.push({index: idx, value: arr2[idx]})
}

Though this seems like kind of a hack around your requirements. 尽管这似乎是围绕您的要求的一种技巧。 Other than this I don't think you have another choice but to loop through either array (optimization: only loop through the smallest one). 除此之外,我认为您别无选择,只能遍历任何一个数组(优化:仅遍历最小的数组)。

If you want the complete result you have to check every element of arr2 for the condition because if you don't there could still be some elements missing from your result. 如果你想完整的结果,你必须检查ARR2的每一个元素的条件,因为如果你不存在仍然可能从你的结果缺少某些元素。

Another solution to this is using reduce() over the arra1 : 另一个解决方案是在arra1使用reduce()

 const arr1 = [0,1,1,0,1]; const arr2 = ["a","b","c","d","e"]; let res = arr1.reduce( (acc, v, idx) => v ? acc.concat({val: arr2[idx], idx}) : acc, [] ); console.log(res); 

Simply use filter : 只需使用filter

 arr1 = [0,1,1,0] arr2 = ['a','b','c','d'] console.log( arr2.filter((item, index) => arr1[index] !== 0) ) 

You can reduce array 1 to the indexes you want and when you need the values you can maps them to their value in array 2 您可以将数组1减少到所需的索引,并且在需要值时可以将它们映射到数组2中的值。

 let arr1 = [0, 1, 1, 0]; let arr2 = ['a', 'b', 'c', 'd']; let indexes = arr1.reduce((results, val, index) => { if (val) { results.push(index); } return results; }, []); console.log(indexes); let vals = indexes.map(idx => arr2[idx]); console.log(vals); 

Try $.each() : 试试$.each()

 $(function() { var arr1 = [0, 1, 1, 0]; var arr2 = ['a', 'b', 'c', 'd']; $.each(arr1, function(k, v) { if (!v) { console.log(arr2[k]); } }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

Obviously, arrays must be of equal size or arr1 can be smaller than arr2 . 显然,数组必须具有相等的大小,否则arr1可以小于arr2

Hope that helps. 希望能有所帮助。

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

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