[英]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
. 我想找到阵列的每个元素都出现
b
的a
。 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.