如何用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,又要同时满足前面的元素条件,逻辑不成立,无法实现需求
正确解法
实现思路
- 先定位到
id匹配的目标元素,获取其索引和cost值 - 从目标元素的前一位开始,向前遍历数组,找到第一个
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
相关产品推荐
相关产品推荐

