[英]How to get all items that are both is array A and B and save them in array C? using javascript without using loops
lets say I have 可以说我有
var A = [x, y, z]
var B = [1, 2, z, 3, x]
How can I get items present both in A and B like so 我如何才能像这样在A和B中同时显示商品
var C = [AB]
Without having to loop through both arrays to check for each iteration 无需遍历两个数组来检查每次迭代
You can use Array.prototype.filter()
and Array.prototype.includes()
to determine if both arrays contain the same element, Set
to remove duplicate elements from resulting array 您可以使用
Array.prototype.filter()
和Array.prototype.includes()
确定两个数组是否包含相同的元素, Set
为从结果数组中删除重复的元素
var A = ["x", "y", "z"] var B = [1, 2, "z", 3, "x"] var C = [...new Set( [...A, ...B].filter(prop => A.includes(prop) && B.includes(prop))) ]; console.log(C);
With duplicates: 重复:
var C = [...A, ...B]
// Result: C = ["x", "y", "z", 1, 2, "z", 3, "x"]
Without duplicates: 没有重复:
var C = [...A, ...B].filter((el, i, a) => i === a.indexOf(el))
// Result: C = ["x", "y", "z", 1, 2, 3]
Update: if you want the intersection of both arrays: 更新:如果要两个数组的交集:
var C = A.filter(function(n) {
return B.indexOf(n) !== -1;
});
// Result: C = ["x", "z"]
let a = new Set(["x", "y", "z"]); let b = new Set([1, 2, "z", 3, "x"]); let intersection = [...a].filter(x => b.has(x)); console.log(intersection);
Sort each array then merge? 对每个数组排序然后合并?
/* sort DESC */
A.sort(function(a,b){ return b-a; })
B.sort(function(a,b){ return b-a; })
then use: 然后使用:
function union_destructive(a, b)
{
var result = [];
while( a.length > 0 || b.length > 0 )
{
if (a[0] > b[0] ){ result.push(a.shift()); }
else if (a[0] < b[0] ){ result.push(b.shift()); }
else /* they're equal */
{
result.push(a.shift());
b.shift();
}
}
return result;
}
( Simplest code for array intersection in javascript ): ( javascript中数组交集的最简单代码 ):
Thats O(n log n). 多数民众赞成O(n log n)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.