Find object in array with next lower value

前端 未结 1 1928
你的背包
你的背包 2021-01-16 03:05

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         


        
1条回答
  •  执笔经年
    2021-01-16 03:58

    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)

    0 讨论(0)
提交回复
热议问题