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

使用JavaScript对比不同结构数组并按条件生成映射数组

Solution

To solve this problem, we need to filter array2 to retain only those objects where their offId (or lowercase offid) value exists in array1. Here's an efficient and clean approach:

Step-by-Step Explanation:

  1. Create a Set from array1: Using a Set allows us to check for the presence of an ID in constant time (O(1)), which is far more efficient than using Array.includes() (which runs in O(n) per check).
  2. Filter array2: Iterate over each object in array2, extract the ID from either the offId or offid property, and check if it exists in our Set. Include the object in the result only if the ID is found.

Code Implementation:

var array1 = ["1", "2", "3", "4", "5", "6"];
var array2 = [ 
  { offId: "4", offname: "four" }, 
  { offId: "9", offname: "nine" }, 
  { offId: "15", offname: "fifteen" }, 
  { offid: "3", offname: "three" }, 
  { offId: "1", offname: "one" }, 
  { offId: "0", offname: "zero" }, 
  { offId: "8", offname: "eight" }, 
  { offId: "10", offname: "ten" }, 
];

// Create a Set for fast ID lookups
const validIds = new Set(array1);

// Filter array2 to get matching objects
const array3 = array2.filter(item => {
  // Get the ID from either offId or offid (handles both property cases)
  const itemId = item.offId ?? item.offid;
  // Check if the ID is in our valid set
  return validIds.has(itemId);
});

console.log(array3);

Expected Output:

[
  { offId: "4", offname: "four" },
  { offid: "3", offname: "three" },
  { offId: "1", offname: "one" }
]

Key Notes:

  • Nullish Coalescing Operator (??): We use this instead of the logical OR (||) because || would treat falsy values (like "0") as "false" and fall back to offid, whereas ?? only falls back if the left-hand side is undefined or null — which is exactly what we need here.
  • Efficiency: Using a Set reduces the time complexity from O(n*m) (if using array1.includes() for each item) to O(n + m), where n is the length of array1 and m is the length of array2. This is especially noticeable with larger arrays.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:09:37