初學者開發人員(JS,ReactNative)。我想匹配作為引數傳遞給函式的 ingridients 陣列,以提取匹配的食譜。我嘗試了不同的函式,如 map 和 filter 但沒有成功。我需要使用 PureJs 函式。
例子 :
Ingridients = ['eggs', 'lemon'] -----> (Passed as a parameter)
Recipies = [
{
_id:1,
_recipieName:"Eggs and Lemon",
_recipieIngridients:["eggs","lemon"]
},
{
_id:2,
_recipieName:"Onther Recipie",
_recipieIngridients:["water","bread","blablabla"]
}
]
i need that result-->
NewArray = [
{
_id:1,
_recipieName:"Eggs and Lemon",
_recipieIngridients:["eggs","lemon"]
}
謝謝。
uj5u.com熱心網友回復:
你應該嘗試這樣的事情:
const availableReciepes = Recipies.reduce((result, reciepe)=>{
let hasAllIngredients = Ingridients.reduce((carry, ingredient)=>{
if(!reciepe.ingredient)
returnn false;
return carry;
}, true);
if(hasAllIngredients){
result.push(reciepe);
}
return result;
}, []);
基本上,對于每個食譜,檢查您是否擁有所有成分,然后將其添加到減少攜帶中。
uj5u.com熱心網友回復:
例如,您可以將成分放入Set以進行有效比較
const recipies = [
{
_id:1,
_recipieName:"Eggs and Lemon",
_recipieIngridients:["eggs","lemon"]
},
{
_id:2,
_recipieName:"Onther Recipie",
_recipieIngridients:["water","bread","blablabla"]
},
{
_id:3,
_recipieName:"Eggs with Cheese Recipie",
_recipieIngridients:["eggs", "cheese"]
}
];
function filterByIngridients(recipies, ingridients, howMatch = 'every') {
const set = new Set(ingridients);
return recipies.filter((r) => {
return r._recipieIngridients[howMatch]((r) => set.has(r));
});
}
現在你可以搭配每一種食材
let output = filterByIngridients(recipies, ['eggs', 'lemon']);
console.log(output);
輸出:
[
{
_id: 1,
_recipieName: 'Eggs and Lemon',
_recipieIngridients: [ 'eggs', 'lemon' ]
}
]
或者一些配料
output = filterByIngridients(recipies, ['eggs', 'lemon'], 'some');
console.log(output);
輸出:
[
{
_id: 1,
_recipieName: 'Eggs and Lemon',
_recipieIngridients: [ 'eggs', 'lemon' ]
},
{
_id: 2,
_recipieName: 'Eggs with Cheese Recipie',
_recipieIngridients: [ 'eggs', 'cheese' ]
}
]
uj5u.com熱心網友回復:
這可以通過執行以下操作來實作
完全符合:
const matchRecipe = (ingredients) =>
Recipies
.filter(r => r._recipieIngridients.length === ingredients.length && r._recipieIngridients.every((ingredient, index) => ingredient === ingredients[index]))
在這里,我過濾使用recipies filter,和作為斷言,我使用的every檢查里面的每個元件_recipieIngridients的每個元件內相匹配ingredients,通過使用index該被取為從第二個引數every函式
如果您不需要它來匹配元素的位置,您可以對兩種成分進行排序,以便它們都應該與之前的順序匹配
不使用嵌套原型函式的更簡化版本:
const matchRecipe = (ingredients) => Recipes.filter(recipe => {
if (ingredients.length !== recipe._recipieIngridients) return false
// Sort both if needed
for (let i = 0; i < recipe._recipieIngridients.length; i ) {
if (recipe._recipieIngridients[i] !== ingredients[i]) return false
}
return false
})
希望你覺得這有幫助
編輯(1)對于您的評論,如果您想要部分匹配,您可以執行以下操作
const matchRecipe = (ingredients) =>
Recipies
.filter(r => r._recipieIngridients.length === ingredients.length && r._recipieIngridients.some((ingredient) => ingredients.include(ingredient)))
some一旦任何元素通過使用該include函式匹配任何成分,原型函式將回傳 true
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/316877.html
標籤:javascript 反应原生
下一篇:React和Typescript,警告:React.createElement:型別無效——需要一個字串但得到:未定義
