For the array of object arrobj
, if the id id
matches with input id idparam
how to get the immediate first larger value cost
object using javascript
Tried
var result = arrobj.find((e, index) => e.id === idparam && arrobj.indexOf(index));
example 1
var idparam1 = 22;
var arrobj1 = [
{id:11, cost: 4},
{id:22, cost: 2}
{id:33, cost: 1},
{id:44, cost: 5}
]
Expected output:
{id:11, cost: 4}
example 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}
]
Expected output:
{id:22, cost: 2}
2
Answers
You can try sorting
Same without sorting
You could simplify this into a traditional for-loop; and return the previous, if larger.