使用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:
- Create a Set from
array1: Using aSetallows us to check for the presence of an ID in constant time (O(1)), which is far more efficient than usingArray.includes()(which runs inO(n)per check). - Filter
array2: Iterate over each object inarray2, extract the ID from either theoffIdoroffidproperty, 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 tooffid, whereas??only falls back if the left-hand side isundefinedornull— which is exactly what we need here. - Efficiency: Using a Set reduces the time complexity from
O(n*m)(if usingarray1.includes()for each item) toO(n + m), wherenis the length ofarray1andmis the length ofarray2. This is especially noticeable with larger arrays.
内容的提问来源于stack exchange,提问作者HKI345
相关产品推荐
相关产品推荐

