Node.js中如何基于另一对象数组值排序同tEnd值的对象数组元素
Hey there! Let's walk through how to solve this problem exactly as you described. Here's a step-by-step implementation with explanations:
Step 1: Create a Score Lookup Map
First, we'll convert the _profsort array into an object (map) for fast score lookups. This avoids looping through the entire _profsort array every time we need a user's score, which is way more efficient.
const _userEnd = [ {"userID":554,"tEnd":6}, {"userID":597,"tEnd":3}, {"userID":605,"tEnd":3}, {"userID":617,"tEnd":1}, {"userID":553,"tEnd":1}, {"userID":616,"tEnd":1}, {"userID":596,"tEnd":0} ]; const _profsort = [ {"userID":596,"score":100}, {"userID":597,"score":85}, {"userID":605,"score":90}, {"userID":617,"score":70}, {"userID":553,"score":75}, {"userID":616,"score":80} // Add other user entries as needed ]; // Create a lookup map: key = userID, value = score const scoreLookup = _profsort.reduce((acc, curr) => { acc[curr.userID] = curr.score; return acc; }, {});
Step 2: Extract and Group Target Elements
Next, we'll pull out the elements from _userEnd that need sorting (indices 1 to 5) and group them by their tEnd value. This lets us handle each set of identical tEnd values separately.
// Extract elements at indices 1-5 (inclusive) const targetElements = _userEnd.slice(1, 6); // Group elements by tEnd value const groupedByTEnd = targetElements.reduce((acc, curr) => { const key = curr.tEnd; if (!acc[key]) { acc[key] = []; } acc[key].push(curr); return acc; }, {});
Step 3: Sort Each Group by Score
Now we'll sort each group using the score from our lookup map. We'll use descending order (highest score first) by default, but you can flip the comparison if you need ascending order instead.
// Sort each group by score (descending order) Object.keys(groupedByTEnd).forEach(key => { groupedByTEnd[key].sort((a, b) => { // Fallback to 0 if a user has no score entry (adjust this as needed) const scoreA = scoreLookup[a.userID] || 0; const scoreB = scoreLookup[b.userID] || 0; return scoreB - scoreA; // Reverse to scoreA - scoreB for ascending order }); });
Step 4: Merge Sorted Groups Back into Original Array
Finally, we'll flatten the sorted groups and replace the original indices (1-5) with the sorted elements. The rest of the array (indices 0 and 6) stays exactly as they were.
// Flatten the sorted groups into a single array const sortedTargetElements = [].concat(...Object.values(groupedByTEnd)); // Create a copy of the original array to avoid mutating it (good practice!) const sortedUserEnd = [..._userEnd]; // Replace indices 1-5 with the sorted elements sortedUserEnd.splice(1, 5, ...sortedTargetElements); console.log(sortedUserEnd);
Quick Notes:
- Mutability: We made a copy of the original array with
[..._userEnd]to avoid changing the original_userEnddirectly. If you don't mind modifying the original, you can skip this step and use_userEnd.splice()directly. - Missing Scores: The code includes a fallback (
|| 0) for cases where a user in_userEnddoesn't have an entry in_profsort. You can tweak this fallback value or add custom error handling if needed. - Sort Order: Swap
scoreB - scoreAwithscoreA - scoreBif you want to sort from lowest to highest score.
内容的提问来源于stack exchange,提问作者Sonu

