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

如何基于temp值为数组对象新增orderTemp属性且不改变原对象顺序

实现方案

核心思路

因为要求不改变原数组的排列顺序,我们通过临时映射的方式计算排名,不直接排序原数组:

  • 先提取原数组所有元素的temp值和对应原始索引,生成临时数组
  • 对临时数组按temp值升序排序(示例中temp越小orderTemp值越小,如需倒序可调整排序规则)
  • 基于排序后的临时数组生成索引到orderTemp的映射关系
  • 最后遍历原数组,给每个元素新增orderTemp属性即可

代码示例

版本1:直接修改原数组中的对象(不改变数组排列顺序)

const originArr = [
  { humidity: 95, location: 'Konstanz', pressure: 1003, temp: 22.46 },
  { humidity: 45, location: 'India', pressure: 1014, temp: 2.23 },
  // 更多元素
];

// 生成带原索引的临时数组并按temp升序排序
const sortedTemp = originArr
  .map((item, idx) => ({ temp: item.temp, index: idx }))
  .sort((a, b) => a.temp - b.temp);

// 给原数组对应位置元素赋值orderTemp
sortedTemp.forEach((item, rank) => {
  originArr[item.index].orderTemp = rank + 1; // 排名从1开始计数
});

console.log(originArr);

版本2:返回全新数组,不修改原数组和原对象

const originArr = [
  { humidity: 95, location: 'Konstanz', pressure: 1003, temp: 22.46 },
  { humidity: 45, location: 'India', pressure: 1014, temp: 2.23 },
];

// 生成原索引到orderTemp的映射
const orderMap = originArr
  .map((item, idx) => ({ temp: item.temp, index: idx }))
  .sort((a, b) => a.temp - b.temp)
  .reduce((map, item, rank) => {
    map[item.index] = rank + 1;
    return map;
  }, {});

// 生成新数组
const result = originArr.map((item, idx) => ({
  ...item,
  orderTemp: orderMap[idx]
}));

console.log(result);

调整说明

如果需要按照temp值从大到小排名,只需要把排序逻辑改为sort((a, b) => b.temp - a.temp)即可。

内容的提问来源于stack exchange,提问作者Kristijan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:06:03