ReactJS实现数组按watch字段降序排序并取前3项
Hey there! Let's walk through how to sort your array and grab the top 3 descending watch values clearly:
Here's a step-by-step solution with explanations for each part:
Sort the array in descending order
The defaultsort()method sorts strings lexicographically, so we need a custom comparator function to sort by numericwatchvalues in descending order. We'll subtract the first object'swatchfrom the second's to reverse the order.Grab the top 3 elements
Useslice(0, 3)to extract the first three items from the sorted array—this gives us the highest three values.Extract only the
watchvalues
Usemap()to pull out just thewatchproperty from each of the top 3 objects, converting the array of objects into an array of numbers.
Full Code Example
const tmp = [{watch: 87}, {watch: 22}, {watch: 68},{watch: 24}, {watch: 35}]; // Chain the methods to get the final result const top3WatchValues = tmp .sort((a, b) => b.watch - a.watch) .slice(0, 3) .map(item => item.watch); console.log(top3WatchValues); // Output: [87, 68, 35]
Quick Note About Mutation
The sort() method mutates the original array. If you want to keep tmp unchanged, make a copy first before sorting:
// Create a copy of the original array to avoid mutation const sortedCopy = [...tmp].sort((a, b) => b.watch - a.watch); const top3WatchValues = sortedCopy.slice(0, 3).map(item => item.watch);
内容的提问来源于stack exchange,提问作者ciokua ciokua

