[英]How to loop through array of objects and check if a value matches either a string in the object or a value in an array of items using lodash
[英]How to loop through each value in array based on other array and check if it matches some condition using javascript?
嗨,我想遍歷兩個 arrays arr1 和 arr2,並使用 javascript 檢查 arr1 中的一個值是否與 arr2 中的每個值匹配。
下面是arrays
const arr1 = [
"item/1/component/1",
"item/1/",
"item-group/1/item/1",
"item/2/component/2",
"item/2",
"item-group/2/item/2/component/2/product/1",
]
const arr2 = [
"1",
"2"
]
現在我想用 arr2 的每個值遍歷 arr1 的每個值,並檢查它是否與“item/arr2 值”匹配
所以對於 arr2 第一個值“1”,我必須遍歷 arr1 的每個值並檢查它是否與字符串“item/1”匹配
所以“item/1/component/1”應該用“item/1”檢查並且不等於“item/1/”應該用“item/1”檢查並且應該對 arr1 中的 rest 個項目做arr2 的第一個值。 如果 arr1 的所有字符串都與 arr2 的第一個值不匹配,它應該返回 true
在這種情況下,應該再次循環遍歷 arr2 的第二個值為“2”的 arr1 項目,並檢查“item/2”並檢查它們是否匹配。 如果 arr1 的至少一個值匹配返回 true
對於 arr2 的所有值,arr1 應該至少匹配一個字符串。 如果它無法匹配 arr2 的至少一個值,它應該返回 false。 我該怎么做? 有人可以幫我解決這個問題嗎? 謝謝。
我是編程新手,長期以來一直試圖找到解決方案,但我無法解決這個問題。 謝謝。
我試過什么?
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr2.length; j++) {
console.log(arr1[i] === `item/${arr2[j]}/`);
}
}
thsi 將為 arr1 的每個值記錄 true 或 false。 但是我想在循環遍歷 arr2 中的所有元素后返回 true 或 false,如果 arr2 值返回 false 失敗一次。
您可以嘗試以下代碼:
const arr1 = [
"item/1/component/1",
"item/1/",
"item-group/1/item/1",
"item/2/component/2",
"item/2",
"item-group/2/item/2/component/2/product/1",
]
const arr2 = [
"1",
"2"
]
function func(){
for (let i = 0; i < arr2.length; i++) {
for (let j = 0; j < arr1.length; j++) {
let temp = "item/"+arr2[i];
if(temp == arr1[j] ){
return true
}
}
}
return false
}
console.log(func())
嘿,不確定你到底在看什么,老實說我不是專家,但我只是希望這可以指導你繼續挑戰:
function checkArrays(array1, array2) {
for(let i=0; i < array1.length; i++) {
for(let j=0; j < array2.length; i++) {
if(array1.indexOf(array2) !== -1) {
return true
} else {
return false
}
}
return true
}
}
console.log(checkArrays(
"item/1/component/1",
"1"
))
您還可以檢查 the.some() 方法,如果至少有一個條件通過,該方法將返回 true。 另一種方法是使用 match() 方法和 Regex or.includes() 方法進行檢查。:)
首先將arr2
元素映射到item2/${a2}
,然后針對這些新值中的每一個檢查arr1
.startsWith()
的每個元素是否。
const arr1 = [ "item/1/component/1", "item/1/", "item-group/1/item/1", "item/2/component/2", "item/2", "item-group/2/item/2/component/2/product/1", ] const arr2 = [ "1", "2" ]; arr2.map(a2 => `item/${a2}`).forEach( a2 => arr1.forEach(a1 => console.log(a2, a1, a1.startsWith( a2 )? true: false )) );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.