You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Array1匹配Array2获取ProductID的jQuery优化方案问询

高效匹配产品ID的优化方案

我有两个数组:

  • Array1:{"Colour":"RASPBERRY","Size":"11"}
  • Array2:产品属性列表,结构如下:
[
  {
    "ProductID": 33043,
    "Key": "Colour",
    "Value": "RASPBERRY"
  },
  {
    "ProductID": 33043,
    "Key": "Size",
    "Value": "4"
  },
  {
    "ProductID": 33044,
    "Key": "Colour",
    "Value": "RASPBERRY"
  },
  {
    "ProductID": 33044,
    "Key": "Size",
    "Value": "5"
  },
  {
    "ProductID": 33045,
    "Key": "Colour",
    "Value": "RASPBERRY"
  },
  {
    "ProductID": 33045,
    "Key": "Size",
    "Value": "6"
  },
  {
    "ProductID": 33046,
    "Key": "Colour",
    "Value": "RASPBERRY"
  },
  {
    "ProductID": 33046,
    "Key": "Size",
    "Value": "7"
  },
  {
    "ProductID": 33047,
    "Key": "Colour",
    "Value": "RASPBERRY"
  },
  {
    "ProductID": 33047,
    "Key": "Size",
    "Value": "8"
  }
]

需求是用Array1的属性从Array2中找出对应的ProductID,但Array2可能有数千条数据,需要避免性能损耗。我自己实现了一段jQuery代码,但觉得性能不够好,寻求更优解决方案:

// Step 1: Group entries in array2 by ProductID
var productDict = {};

$.each(array2, function(index, entry) {
    var productID = entry.ProductID;
    var key = entry.Key;
    var value = entry.Value;

    if (!productDict[productID]) {
        productDict[productID] = {};
    }
    productDict[productID][key] = value;
});

// Step 2: Check each ProductID group against the criteria in array1
var matchingProductIDs = [];

$.each(productDict, function(productID, attributes) {
    var match = true;
    $.each(array1, function(key, value) {
        if (attributes[key] !== value) {
            match = false;
            return false; // Break out of the loop
        }
    });
    if (match) {
        matchingProductIDs.push(productID);
    }
});

// Output the result
console.log("Matching Product IDs:", matchingProductIDs);

优化方案

核心思路

原代码先分组所有产品属性再逐个校验,虽然逻辑清晰,但需要两次遍历,且要存储所有产品的完整属性,内存开销大。优化思路是统计每个ProductID满足Array1条件的次数,当次数等于Array1的条件总数时,即为匹配的ID,只需要一次遍历Array2,性能和内存占用都更优。

优化代码

// 提取查询条件并记录需要满足的条件数量
const criteria = Array1;
const requiredMatches = Object.keys(criteria).length;

// 统计每个ProductID匹配的条件数
const matchCounter = {};
const matchingIds = [];

// 原生for...of循环遍历Array2,性能优于jQuery.each
for (const item of Array2) {
  const pid = item.ProductID;
  // 仅处理符合查询条件的条目
  if (criteria[item.Key] === item.Value) {
    matchCounter[pid] = (matchCounter[pid] || 0) + 1;
    // 当匹配数等于所需条件数时,加入结果集
    if (matchCounter[pid] === requiredMatches) {
      matchingIds.push(pid);
    }
  }
}

console.log("匹配的产品ID:", matchingIds);

性能优势

  • 时间复杂度:原方案为O(N + M)(N是Array2长度,M是产品分组数),优化方案为O(N),仅需一次遍历。
  • 内存占用:优化方案无需存储所有产品的完整属性,仅记录匹配计数,内存开销大幅降低。
  • 循环效率:原生for...of循环比jQuery的$.each减少了回调函数的额外开销,进一步提升性能。

内容的提问来源于stack exchange,提问作者user3050803

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 22:35:54