[英]Check if an array contains 2 or more elements of another array in JavaScript
我在這里找到了與我的問題類似的答案:檢查一個數組是否包含 JavaScript 中另一個數組的任何元素,不幸的是,OP 詢問是否 ANY 元素等於另一個數組中的 ANY 元素。
就我而言,我實際上需要檢查two or more elements equal to 2 or more elements in another array
。 否則,它應該返回 false。
我嘗試了與上述問題類似的方法,但我無法將它定位到 X 個匹配項......
Array.filter(el => el.colors.some(x => colors2.includes(x)))
這僅適用於任意數量的比賽......
首先,您可以使用array#filter
結合array#includes
在 arr2 中查找 arr1 中的所有項目。
然后檢查結果的長度。
let arr1 = [1, 2, 3]; let arr2 = [2, 3]; let result = arr1.filter(v1 => arr2.includes(v1)); console.log(result.length >= 2);
如果這有用的話,我在下面有這樣的工作。 以MDN為例並稍作修改。
我會用@Nguyễn Văn Phong 回答 go。 另外,如果您想保持代碼整潔,我會使用下划線庫或類似庫。 這只是我個人的喜好:)
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction',
'present'];
const result = words.filter(word => word.length > 6 );
const result1 = result.includes('exuberant');
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
console.log(result1);
// expected output: true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.