1樓:nbili
給個繞的寫法
let a = ["stewed", "tomatoes", "and", "macaroni"];
let b = ["macaroni", "and", "cheese"];
function intersect(a, b) else if (b.includes(a[0return [a[0], ...intersect(a.
slice(1), b)];
} else else if (b.includes(a[0return union(a.slice(1), b);
} else {
return [a[0], ...union(a.slice(1), bconsole.log(intersect(a, b));
console.log(union(a, b));
2樓:ten90
並集:let arr1 = [1, 2, 3];
let arr2 = [1, 2, 4, 5];
let set = new Set([...arr1, ...arr2])
console.log(set); //
交集:let arr1 = [1, 2, 3];
let arr2 = [1, 2, 4, 5];
let arr3 = arr1.filter(items => arr2.indexOf(items) != -1);
console.log(arr3); //[ 1, 2 ]差集:let arr1 = [1, 2, 3];
let arr2 = [1, 2, 4, 5];
let arr3 = arr1.filter(items => arr2.indexOf(items) == -1);
console.log(arr3); //[ 1, 2 ]
3樓:楓橋夜泊
我現在想快速實現這樣乙個, 找出乙個陣列在另外乙個陣列中存在的一項,並對其進行操作
array1.fliter(v => array2.includes(v)).forEach(m => m.checked = true)
但是這個陣列中的是物件, 我只想找到他們乙個物件的屬性相同的一項,如何快速操作?我現在這樣就必須保證物件裡的要完全相同,哪怕是字段的順序都要相同,以前老是寫雙迴圈,太煩
4樓:mcZone
ES6中使用Set結構:
leta
=new
Set([1,
2,3]);
letb
=new
Set([3,
5,2]);
// 並集
letunionSet
=new
Set([...a,
...b
]);//[1,2,3,5]
// 交集
letintersectionSet
=new
Set([...a].
filter(x
=>b.
has(
x)));
// [2,3]
// ab差集
letdifferenceABSet
=new
Set([...a].
filter(x
=>!b
.has(x
)));
// [1]
再把Set轉換為陣列即可.
letarr
=Array
.from
(set
);// 或 let arr = [...set];
5樓:尤雨溪
目前的解法都有一些小問題啦。比如先轉成 object hash 的話不能處理物件陣列。indexOf 則是有個永遠對 NaN 返回 -1 的問題。
ES7 Array.prototype.includes (stage 2 proposal) 還算比較簡潔:
letintersection=a
.filter(v
=>b.
includes(v
))let
difference=a
.concat(b
).filter(v
=>!a
.includes(v
)||!b
.includes(v))
6樓:
相同的a.
filter
(function(v
))不同的
a.filter(function(v)).concat(b.filter(function(v)))
7樓:
用Underscore.js
intersection
_.intersection(*arrays)
Computes the list of values that are the intersection of all thearrays. Each value in the result is present in each of thearrays.
_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]
difference
_.difference(array, *others)
Similar towithout, but returns the values fromarraythat are not present in theotherarrays.
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]
但是這個只能用於原生型別,如果想要用於物件陣列的話,丟個鏈結在這裡http://
8樓:蘇鑫
// 定義陣列
a = [1,2,3,4,5,6,7,8,9,10]b = [3,2,6,7,8,100,24]// 把a陣列轉化成object
var hash = {};
for(var i=0,max=a.length; i hash[a[i]] = true; } // 通過hash檢測b陣列中的元素for(var i=0, max=b.length; i else} 周中原 邏輯運算不一定返回false或者true,還有可能返回其他值。題主只問了undefined和null,另外送NaN的情況 免費 與 運算元中任意乙個是null undefined NaN,則返回對應的null undefined NaN 例如 null 任意型別 返回null 若兩個運算元是... 胡小濺 你說反了,Promise 的狀態就是靠外界修改的。它自己並不會自發地從 Pending 變成 Resolved,它只是將可以改變內部狀態的 resolve 和 reject 方法暴露出來,由使用者決定什麼時候改變狀態。唯一的限制是狀態只能改變一次,一旦從 Pending 變為其它狀態就不再受... 混混蛋 Object.keys obj 返回obj的自身 不包含原型鏈上的 的所以可列舉屬性的名字陣列 for in迴圈則包含原型鏈.for name in obj Object.getOwnPropertyNames obj 返回obj自身 不含原型鏈上的 的所有屬性名陣列,包括不可列舉的 想要獲...請問在javascript中undefined和null與其他字串的進行邏輯運算有什麼規律嗎?感覺好亂 這個有用嗎?
如何理解 Javascript 中的 Promise 物件的狀態不受外界影響?
javascript中object keys方法使用的問題(實操和書上寫的不相符)?