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

如何用JavaScript获取匹配指定id对象的首个更大cost值对象

问题:查找匹配元素前首个cost更大的对象

需求:给定对象数组arrobj,找到其中id与输入参数idparam匹配的元素,然后获取该元素之前首个cost值大于它的对象。

用户尝试的错误代码:

var result = arrobj.find((e, index) => e.id === idparam && arrobj.indexOf(index));

示例说明

示例1

var idparam1 = 22; 
var arrobj1 = [
  {id:11, cost: 4},
  {id:22, cost: 2},
  {id:33, cost: 1},
  {id:44, cost: 5} 
];

期望输出:

{id:11, cost: 4}

示例2

var idparam2 = 33; 
var arrobj2 = [
  {id:11, cost: 4},
  {id:22, cost: 2},
  {id:33, cost: 1},
  {id:44, cost: 5},
  {id:54, cost: 6} 
];

期望输出:

{id:22, cost: 2}

错误代码分析

  • arrobj.indexOf(index)逻辑错误:indexOf用于查找元素在数组中的索引,传入索引值完全不符合该方法的使用场景
  • find回调逻辑混乱:既要匹配目标id,又要同时满足前面的元素条件,逻辑不成立,无法实现需求

正确解法

实现思路

  1. 先定位到id匹配的目标元素,获取其索引和cost值
  2. 从目标元素的前一位开始,向前遍历数组,找到第一个cost大于目标元素cost的对象

代码实现

function findPrevHigherCostObj(arrobj, idparam) {
  // 找到目标元素的索引
  const targetIndex = arrobj.findIndex(item => item.id === idparam);
  // 没找到匹配元素则返回null
  if (targetIndex === -1) return null;
  
  const targetCost = arrobj[targetIndex].cost;
  // 从目标元素前一位开始向前遍历
  for (let i = targetIndex - 1; i >= 0; i--) {
    if (arrobj[i].cost > targetCost) {
      return arrobj[i];
    }
  }
  // 前面没有符合条件的元素返回null
  return null;
}

测试示例

测试示例1

console.log(findPrevHigherCostObj(arrobj1, idparam1));
// 输出:{id:11, cost: 4}

测试示例2

console.log(findPrevHigherCostObj(arrobj2, idparam2));
// 输出:{id:22, cost: 2}

补充说明

  • 如果目标元素是数组第一个元素,或者前面没有cost更大的元素,函数返回null,可根据实际需求调整返回值
  • 使用findIndex定位目标元素比indexOf更可靠,避免数组中存在重复对象时的索引错误问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 00:27:48