![](/img/trans.png)
[英]how to get all the children of a node as items of an array in javascript using jQuery
[英]How to get all items that are both is array A and B and save them in array C? using javascript without using loops
可以說我有
var A = [x, y, z]
var B = [1, 2, z, 3, x]
我如何才能像這樣在A和B中同時顯示商品
var C = [AB]
無需遍歷兩個數組來檢查每次迭代
您可以使用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);
重復:
var C = [...A, ...B]
// Result: C = ["x", "y", "z", 1, 2, "z", 3, "x"]
沒有重復:
var C = [...A, ...B].filter((el, i, a) => i === a.indexOf(el))
// Result: C = ["x", "y", "z", 1, 2, 3]
更新:如果要兩個數組的交集:
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 DESC */
A.sort(function(a,b){ return b-a; })
B.sort(function(a,b){ return b-a; })
然后使用:
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;
}
多數民眾贊成O(n log n)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.