簡體   English   中英

是否有一個Javascript函數用於檢查數組數組是否包含特定數組?

[英]Is there a Javascript function for checking if an array of arrays contains a specific array?

我正在制作一個Javascript應用程序,我需要為每個包含兩個對象的特定數組檢查一個數組數組(一個嵌套數組)。 嵌套數組看起來有點像這樣: [[obj1, obj2], [obj2, obj3], [obj3, obj1]]

我遇到的問題是,即使應用程序的這一部分沒有引發任何錯誤,它也無法正常工作。 我嘗試這樣做: array.includes([obj1, obj2]) ,但這會返回false,即使數組確實包含[obj1, obj2]

那么為什么這不是按照預期的方式工作,對於這種情況有什么更好的方法呢?

編輯:我想檢查數組中包含的對象的嚴格比較,無論包含它們的數組的引用。 我怎樣才能做到這一點?

includes===比較,顯然你的搜索數組只相當於其中一個條目,而不是相同的實際數組。

您可以使用some回調檢查被訪問的數組中的every條目是否與您的搜索數組匹配。

const flag = arrayOfArrays.some(
    array => array.length === search.length && array.every(
        (entry, index) => entry === search[index]
   )
);

請注意,這假設內部條目與===相當。 如果沒有,用適當的方式替換它們。

實例:

 function check(arrayOfArrays, search) { return arrayOfArrays.some( array => array.length === search.length && array.every( (entry, index) => entry === search[index] ) ); } console.log( "yes:", check( [[1, 2], [3, 4], [5, 6], [7, 8]], [5, 6] ) ); console.log( "no:", check( [[1, 2], [3, 4], [5, 6], [7, 8]], [6, 5] // Note the different order ) ); 

如果要在數組數組中找到數組,可以使用find而不是some數組。 如果要在數組數組中找到其索引 ,可以使用findIndex

在JS中,每個數組(對象)都是唯一的,即使它具有與另一個相同的內容:

 console.log( {} == {} ); // false console.log( [] == [] ); // false console.log( [1, 2] == [1, 2] ); // false 

因此,您必須逐個循環並比較每個元素:

 let arr = [ [0, 0, 0], [1, 1, 1], [2, 2, 2], ] console.log( arrInArr( arr, [3, 3, 3] ) ); // false arr[3] = [3, 3, 3]; // new elem added console.log( arrInArr( arr, [3, 3, 3] ) ); // true function arrInArr(mama, child){ for( let i = 0; i < mama.length; i++ ){ // don't even starting to compare if length are not equal if( mama[i].length != child.length ){ continue } let match = 0; // To count each exact match for( let j = 0; j < child.length; j++ ){ if( mama[i][j] === child[j] ){ // We made sure, that they have equal length, and can use index 'j' // to compare each element of arrays. match++; } else { break; } } if( match === child.length ){ // If each element exactly matched return true; } } return false; } 

如果你使用一個包狀lodash,它有比較的方法,如果兩個對象是通過內容而不是通過更嚴格相等===比較: https://lodash.com/docs/4.17.15#isEqual

使用_.isEqual ,您可以執行以下操作:

array.findIndex(item => _.isEqual(item, testObject)) >= 0

Lodash甚至可能有一種方法來直接搜索具有深度等於比較的數組,但上面的內容將完成工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM