admin管理员组文章数量:1321837
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
. i.e. I want a resultant array like this:
result = [1, 1, 2, 5, 5]
I was going through the Lodash docs to find any bination of methods which would give me the result, but haven't managed to do so. Does anyone know how I can get the result
array? I prefer to use a very concise solution (i.e. without too many loops etc), and usually Lodash is best for that, but other solutions are also fine.
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
. i.e. I want a resultant array like this:
result = [1, 1, 2, 5, 5]
I was going through the Lodash docs to find any bination of methods which would give me the result, but haven't managed to do so. Does anyone know how I can get the result
array? I prefer to use a very concise solution (i.e. without too many loops etc), and usually Lodash is best for that, but other solutions are also fine.
3 Answers
Reset to default 7You'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
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.
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/lodash/4.16.4/lodash.min.js"></script>
本文标签: Find all occurrences of each element of an array in another array in JavascriptStack Overflow
版权声明:本文标题:Find all occurrences of each element of an array in another array in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742103237a2420899.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论