簡體   English   中英

在javascript中搜索對象數組以查找另一個數組的最佳方法是什么?

[英]What is the best way to search an array of objects to find another array in javascript?

所以,假設我正在制作一個烹飪游戲。 我有一個像這樣的對象數組:

const recipes = [
  {
    "ingredients": ["Bun", "Patty"],
    "name": "Hamburger"
  },
  {
    "ingredients": ["Hamburger", "Cheese"],
    "name": "Cheeseburger"
  }
  
]

然后我有按鈕,當用戶點擊按鈕時,他們的選擇被添加到這樣的數組中:

userChoices = ["Hamburger", "Cheese"]

順序在這里無關緊要。 無論順序如何,遍歷對象數組以查找與 userChoices 匹配的數組的最佳方法是什么?

更新:這是我用來比較用戶選擇和食譜的內容,但我需要知道是否有更簡單的方法來迭代它? 我是 JS 新手

function arrayEquals(a, b) {
  return Array.isArray(a) &&
    Array.isArray(b) &&
    a.length === b.length &&
    a.every((val, index) => val === b[index]);
}

假設您需要:

  • 相同的長度
  • 相同的內容
  • 任何訂單

有一個通過定義自定義相等比較器的解決方案。

比較器顯示在這篇文章中: https : //www.30secondsofcode.org/articles/s/javascript-array-comparison

const equalsIgnoreOrder = (a, b) => {
  if (a.length !== b.length) return false;
  const uniqueValues = new Set([...a, ...b]);
  for (const v of uniqueValues) {
    const aCount = a.filter(e => e === v).length;
    const bCount = b.filter(e => e === v).length;
    if (aCount !== bCount) return false;
  }
  return true;
}

const result = recipes.filter(x => equalsIgnoreOrder(x.ingredients, userChoices));
console.log(result);

這使:

[{
  ingredients: ["Hamburger", "Cheese"],
  name: "Cheeseburger"
}]

此外,如果您交換元素,結果將是相同的。 但是,如果您嘗試:

userChoices = ["Cheese", "Cheese"]

沒有匹配。

暫無
暫無

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

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