数组值筛选更新问题:合并两数组并按值保留/新增元素
Solution for Merging and Filtering Arrays Based on Value Matching
Alright, let's tackle this problem step by step. Based on your rules, we need to filter the first array, add new items from the second array, and assign new IDs correctly. Here's how to do it in JavaScript:
Step-by-Step Logic
- First, extract all values from
Array2into a set for quick lookup (this makes checking existence way faster). - Filter
Array1to keep only objects whosevalueexists inArray2. - Identify items in
Array2whosevaluedoesn't appear inArray1. - Generate new unique IDs for these new items: we'll take the highest ID from the filtered
Array1and increment from there. - Combine the filtered
Array1and the new items to get yourAfterArray.
Code Implementation
// Your sample arrays const Array1 = [ { id: '1', value: 'a' }, { id: '2', value: 'b' } ]; const Array2 = [ { id: '', value: 'c' }, { id: '', value: 'd' }, { id: '', value: 'a' } ]; // Step 1: Get all values from Array2 for quick lookup const array2Values = new Set(Array2.map(item => item.value)); // Step 2: Filter Array1 to keep only items with value present in Array2 const filteredArray1 = Array1.filter(item => array2Values.has(item.value)); // Step 3: Get values from filtered Array1 to check against Array2 const filteredArray1Values = new Set(filteredArray1.map(item => item.value)); // Step 4: Extract new items from Array2 (values not in filtered Array1) const newItemsFromArray2 = Array2.filter(item => !filteredArray1Values.has(item.value)); // Step 5: Generate new IDs for the new items // First, find the highest existing ID in filteredArray1 const maxExistingId = filteredArray1.length ? Math.max(...filteredArray1.map(item => parseInt(item.id, 10))) : 0; // Assign incrementing IDs to new items const newItemsWithIds = newItemsFromArray2.map((item, index) => ({ id: (maxExistingId + index + 1).toString(), value: item.value })); // Step 6: Combine filtered Array1 and new items to get AfterArray const AfterArray = [...filteredArray1, ...newItemsWithIds]; console.log(AfterArray); // Output: [ { id: '1', value: 'a' }, { id: '3', value: 'c' }, { id: '4', value: 'd' } ]
Notes on Edge Cases
- If
Array1is empty: The first new item will get ID1, sincemaxExistingIddefaults to0. - If
Array2has duplicate values: The code above will add multiple entries for the same value (e.g., twocitems inArray2will become two new items with IDs3and4). If you want to avoid duplicates, add a step to deduplicatenewItemsFromArray2first, like using a set to track unique values before mapping to new IDs. - Ensure all IDs in
Array1are numeric strings (the code usesparseIntto handle them; non-numeric IDs would need extra handling).
内容的提问来源于stack exchange,提问作者userlkjsflkdsvm
相关产品推荐
相关产品推荐

