简体   繁体   English

在Javascript中查找另一个数组中数组的每个元素的所有出现

[英]Find all occurrences of each element of an array in another array in Javascript

I have an array here: 我这里有一个数组:

a = [1, 1, 2, 3, 4, 5, 5, 6, 7, 7]

and another, 另一个,

b = [1, 2, 5]

I want to find all occurrences of each element of array b in a . 我想找到阵列的每个元素都出现ba ie I want a resultant array like this: 即我想要一个像这样的结果数组:

result = [1, 1, 2, 5, 5]

I was going through the Lodash docs to find any combination of methods which would give me the result, but haven't managed to do so. 我正在浏览Lodash文档 ,找到可以给我结果的任何方法组合,但是没有设法这样做。 Does anyone know how I can get the result array? 有谁知道我怎么能得到result数组? I prefer to use a very concise solution (ie without too many loops etc), and usually Lodash is best for that, but other solutions are also fine. 我更喜欢使用一个非常简洁的解决方案(即没有太多的循环等),通常Lodash最好,但其他解决方案也很好。

You'd just filter the first array based on the second array 您只需根据第二个数组过滤第一个数组

 var a = [1, 1, 2, 3, 4, 5, 5, 6, 7, 7]; var b = [1, 2, 5]; var result = a.filter( z => b.indexOf(z) !== -1 ); console.log(result); 

You can use for..of loops to iterate b check if element of a is equal to current element in b 您可以使用for..of循环迭代b检查的元素a等于在当前元素b

 let a = [1, 1, 2, 3, 4, 5, 5, 6, 7, 7]; let b = [1, 2, 5]; let result = []; for (let prop of b) { for (let el of a) { if (el === prop) result = [...result, el] } } console.log(result); 

If you really wanted to use _, you could use 2 _.difference calls. 如果你真的想使用_,你可以使用2个_difference调用。

 var a = [1, 1, 2, 3, 4, 5, 5, 6, 7, 7]; var b = [1, 2, 5]; var result = _.difference(a,_.difference(a,b)); console.log(result); 
 <script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script> 

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

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