如何在多维数组与一维对象中匹配ID,避免过多嵌套循环?
Optimizing ID Matching Between Nested Arrays and Objects
Hey there! I see you've got a working solution using nested map calls, but we can definitely make this more efficient—especially if your dataset grows larger. Let's break down the issues with the original approach and build a better version.
What's Less Efficient in the Original Code
- You're looping through all keys in
storedOBJfor every single question—that's a lot of redundant checks. If you have 100 pages, 10 questions per page, and 50 entries instoredOBJ, that's 50,000 extra iterations! - Using nested
mapplus manualpushto build the result array works, but it's a bit clunky and harder to read at a glance.
A Faster, Cleaner Approach
Instead of checking every key in storedOBJ for each question, we can leverage object key lookups (which are O(1) time!) and use array methods that streamline the process:
const getMatchingIDs = function(pages, storedOBJ) { // Use flatMap to flatten nested results in one go return pages.flatMap(page => page.questions // First, filter out questions that don't exist in storedOBJ (skip unnecessary work) .filter(question => storedOBJ.hasOwnProperty(question.questionText)) // For matching questions, build the ID pair directly .map(question => { const answerIndex = storedOBJ[question.questionText]; const answerID = question.answers[answerIndex].id; return `${question.id}:${answerID}`; }) ); };
Why This Works Better
- O(1) Key Lookups: Instead of looping through all
storedOBJkeys for each question, we just check if the question's text exists as a key, then grab the index instantly. This drops the time complexity fromO(P*Q*S)toO(P*Q)(P = number of pages, Q = questions per page, S = entries in storedOBJ). flatMapfor Clean Flattening: No more manually pushing to an array—flatMaphandles turning nested question results into a single flat array automatically.- Early Filtering: We filter out non-matching questions first, so we don't waste time processing questions that have no corresponding entry in
storedOBJ.
Testing with Your Sample Data
Let's plug in your example to confirm it works:
const pages = [ { questions: [ { id: 987, questionText: 'Some Question', answers: [{ id: 154 }, { id: 232 }, { id: 312 }] }, { id: 324, questionText: 'Another Question', answers: [{ id: 154 }, { id: 232 }, { id: 312 }] }, { id: 467, questionText: 'Last Question', answers: [{ id: 154 }, { id: 232 }, { id: 312 }] } ] } ]; const storedOBJ = { 'Some Question': 0, 'Last Question': 0, 'Another Question': 2 }; console.log(getMatchingIDs(pages, storedOBJ)); // Output: ["987:154", "324:312", "467:154"] — exactly what you need!
Bonus: Add Safety Checks
If you want to handle edge cases (like invalid answer indexes), you can add a quick validation step:
.map(question => { const answerIndex = storedOBJ[question.questionText]; // Make sure the index is a valid number within the answers array bounds if (typeof answerIndex === 'number' && answerIndex >= 0 && answerIndex < question.answers.length) { const answerID = question.answers[answerIndex].id; return `${question.id}:${answerID}`; } // Optional: Return null or skip invalid entries return null; }) // Filter out any null results from invalid indexes .filter(Boolean)
内容的提问来源于stack exchange,提问作者Jaeeun Lee
相关产品推荐
相关产品推荐

