如何在TypeScript中使用Map-Reduce筛选skills属性最大值的列表项?
Got it, let’s work through this problem using Reduce (combined with array operations) to get all items with the maximum skills value, as you requested. Here are two solid approaches tailored for TypeScript:
Approach 1: Two-step Reduce + Filter (Clear and Readable)
First, we’ll use reduce to find the highest skills value in the array, then filter the original array to grab all items matching this max value. This logic is straightforward and easy to follow:
const scores = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}, {name: "D", skills: 60, result: 70}]; // Use reduce to determine the maximum skills value const maxSkillValue = scores.reduce((currentMax, item) => { return item.skills > currentMax ? item.skills : currentMax; }, -Infinity); // Initialize with -Infinity to handle negative skill values if needed // Filter to get all items with the max skill value const output = scores.filter(item => item.skills === maxSkillValue); console.log(output); // Output: [{name: "C", skills: 60, result: 60}, {name: "D", skills: 60, result: 70}]
I used -Infinity as the initial value instead of 0 to cover edge cases where skill values might be negative—this ensures we always find the true maximum regardless of the data range.
Approach 2: Single-pass Reduce (More Efficient)
If you want to optimize for performance (especially with large arrays), we can do everything in one reduce call. This way we only iterate over the array once, collecting all items that have the current maximum skills value as we go:
const scores = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}, {name: "D", skills: 60, result: 70}]; const output = scores.reduce((accumulator, currentItem) => { // If we haven't collected any items yet, start with the current one if (accumulator.length === 0) { return [currentItem]; } const currentMaxSkill = accumulator[0].skills; // Current item has a higher skill value than our current max—reset the accumulator if (currentItem.skills > currentMaxSkill) { return [currentItem]; } // Current item matches the max skill value—add it to the accumulator else if (currentItem.skills === currentMaxSkill) { accumulator.push(currentItem); } // If current item's skill is lower, keep the accumulator as-is return accumulator; }, [] as typeof scores); // Type assertion to keep TypeScript's type checker happy console.log(output); // Same expected output as above
This approach avoids a second array traversal with filter, which can make a noticeable difference when working with large datasets.
内容的提问来源于stack exchange,提问作者ImtiazNur

