根据范围返回数组中的对象

时间:2019-07-16 23:55:31

标签: javascript arrays

我有一个对象数组。

var array = [{"First object", 15}, {"Second object", 20}];

我使对象构造函数起作用,因此值的名称为titleheight

如何在每个数组的高度值之间的范围内创建一个返回值的函数。假设我叫currentObject(17),我想返回第二个对象。如果我调用currentObject(10),我想返回此数组中的第一个对象。

var array = [{"First object", 15}, {"Second object", 20}];

function currentObject(height) {
  // return object that is between the smallest closest number to height 
  // and the height-value of the object before it.
}

我已经尝试过使用.filter.find的几种选择,但我还无法解决。我曾考虑过在数组中添加startHeightendHeight,但是我认为由于范围是从上一个对象开始的,因此会有很多冗余数据。

1 个答案:

答案 0 :(得分:1)

你想要的是减少

const currentObject = (height, data) => data.reduce((result, current) => Math.abs(result.height - height) > Math.abs(current.height - height) ? current : result);

这将遍历数据数组,如果每个循环都更接近高度,则每个循环将替换累加器。您的最终累加器将是最接近高度的结果。