You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS实现数组按watch字段降序排序并取前3项

Hey there! Let's walk through how to sort your array and grab the top 3 descending watch values clearly:

Sorting & Filtering the Array for Top 3 Watch Values

Here's a step-by-step solution with explanations for each part:

  1. Sort the array in descending order
    The default sort() method sorts strings lexicographically, so we need a custom comparator function to sort by numeric watch values in descending order. We'll subtract the first object's watch from the second's to reverse the order.

  2. Grab the top 3 elements
    Use slice(0, 3) to extract the first three items from the sorted array—this gives us the highest three values.

  3. Extract only the watch values
    Use map() to pull out just the watch property 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:22:53