I need to get the next lower object in an array using a weight value.
const data = [
{ weight: 1, size: 2.5 },
{ weight: 2, size: 3.0 },
{ weight: 4, s
If the objects' weights are in order, like in the question, one option is to iterate from the end of the array instead. The first object that matches will be what you want.
If the .find
below doesn't return anything, alternate with || data[0]
to get the first item in the array:
const data = [
{ weight: 1, size: 2.5 },
{ weight: 2, size: 3.0 },
{ weight: 4, size: 3.5 },
{ weight: 10, size: 4.0 },
{ weight: 20, size: 5.0 },
{ weight: 30, size: 6.0 }
]
const output = data.reverse().find(({ weight }) => weight < 19) || data[0];
console.log(output);
(if you don't want to mutate data
, you can .slice
it first)