I have this payload which I'm trying to execute some functions on in JavaScript:
{
"markets": [
{
"mtId": 27,
"id": 1,
"cId": "27-1",
"mt": "OVER_UNDER",
"selections": [
{
"id": 1,
"price": 1.0896773820446435,
"selectionStatus": 1,
"name": "Over 0.5"
},
{
"id": 2,
"price": 12.159031085167172,
"selectionStatus": 1,
"name": "Under 0.5"
}
],
"marketName": "Over Under 0.5"
},
{
"mtId": 27,
"id": 2,
"cId": "27-2",
"mt": "OVER_UNDER",
"selections": [
{
"id": 1,
"price": 1.4531444546407393,
"selectionStatus": 1,
"name": "Over 1.5"
},
{
"id": 2,
"price": 3.207355058969988,
"selectionStatus": 1,
"name": "Under 1.5"
}
],
"marketName": "Over Under 1.5"
},
{
"mtId": 27,
"id": 3,
"cId": "27-3",
"mt": "OVER_UNDER",
"selections": [
{
"id": 1,
"price": 2.3859593325595307,
"selectionStatus": 1,
"name": "Over 2.5"
},
{
"id": 2,
"price": 1.721681322609395,
"selectionStatus": 1,
"name": "Under 2.5"
}
],
"marketName": "Over Under 2.5"
}
]
}
Basically, I want to take the markets array, map the selections and
- return the array with price differences from 0.5.
- I'd then like to take that array and return the value which is closest to zero.
I can get the result from this function:
export const generateNumberClosestToZero = (markets) => {
let goal = 0;
let result = markets
.map((market) =>
market.selections.reduce(function (bookPercentage, selection) {
return 0.5 - 1 / selection.price;
}, 0)
)
.reduce(function (prev, current) {
return Math.abs(current - goal) < Math.abs(prev - goal) ? current : prev;
});
return result;
};
But what I want to do is also retrieve the index of that reduced value, so I can perform operations on that specific market (e.g. markets[1] etc. ). Is there a way to do this with my code, or a better solution than what I have so far?