[英]Compare array by value or group of values
假設我有陣列1
const arr1 = [[45, 63],[89],[90]]
和數組2
const arr2 = [45, 63]
要檢查arr2中是否存在arr2或arr2中的值,可以輕松執行下一個功能
private contains(arr1, opts) {
const stringifiedOpts = JSON.stringify(opts);
return arr1.some(item => JSON.stringify(item) === stringifiedOpts);
}
在這種情況下contains()函數將返回true。
這是第一個最簡單的案例。 現在讓我們說:
arr2 = [45, 63, 90]
function contains()將返回false,因為arr1不包含[45,63,90]但包含[90]作為不同的數組。 在這種情況下,函數應該返回true,因為在arr1中存在來自arr2的90
我的問題是,在以下情況下,我應該在該函數中使用什么樣的邏輯來返回true:
arr2 = [45,63,90]或
arr2 = [45,90]或
arr2 = [63,89]或
arr2 = [63,90]或
arr2 = [81,20,90]或
arr2 = [25,60,89]
因為在arr1中存在90或89但是作為不同的數組
這里有任何幫助/想法/解決方案,歡迎大家。 謝謝!
這似乎有效:
arr1
.map(arr => arr.join())
.some(arr => arr2.join().includes(arr))
這是一個沒有展平的版本來保持結構,它基本上檢查arr1中的每個塊是否符合arr2。
const arr1 = [[45, 63],[89],[90]]; function contains(arr, opts) { for(let i=0; i<arr.length; i++) { let innerArray = arr[i]; let isThisBlockOk = true; for(let j=0; j<innerArray.length; j++) { if(opts.indexOf(innerArray[j]) === -1) { isThisBlockOk = false; break; } } if(isThisBlockOk) return true; } return false; } const listOfArr2 = [ [45, 63], [45, 63, 90], [45, 63, 90], [45, 90], [63, 89], [63, 90], [81, 20, 90], [25, 60, 89], [45, 64, 91], [45] ]; listOfArr2.forEach(arr2 => { console.log(JSON.stringify(arr2) + ' contains return: '+ contains(arr1, arr2)); });
這是你想要的嗎? 我猜測並需要你的反饋
const arr1 = [ [45, 63], [89], [90] ] document.write(custom_contains_any(arr1, [63, 88])) document.write('<br>') document.write(custom_contains_all(arr1, [63, 90])) function custom_contains_any(source, search) { const s1 = flaten(source) const s2 = flaten(search) return s2.filter((x) => s1.includes(x)).length } function custom_contains_all(source, search) { const s1 = flaten(source) const s2 = flaten(search) return s2.every((x) => s1.includes(x)) } function flaten(arr) { let rtn = [] arr.forEach((x) => { if (Array.isArray(x)) { rtn = [...rtn, ...flaten(x)] return } rtn = [...rtn, x] }) return rtn }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.