javascript - 查找具有较高项但低于限制的对象的 id

标签 javascript arrays node.js sorting

我有一个javascript对象数组,该对象是这样的:

smil
.____.update (object)
|    |...
|
|____.stream (array)
|    |...
|
|____.playlist (array of object)
    |____.name (string)
    |____.scheduled
    |____...

Scheduled 是一个日期,我编写了一个函数以 Date 对象的形式获取它。

现在,我需要在 smil.playlist 中找到过去的对象的 id(低于新的 Date 对象)并且更接近它。

在之前的版本中,我使用过滤、排序和弹出来获取对象,但是随着应用程序结构的变化,我现在需要它的 id。

旧代码:

function get_last_playlist(smilp){
    //get current date
    time = new Date();
    //Delete all of playlist which are in the future
    smilp.filter(function(element) {
        return time.getTime() > gettime(element.scheduled).getTime();
    });
    //Sort by close to current time (higher scheduled)
    smilp.sort(function(a, b) {
        return gettime(a.scheduled) - gettime(b.scheduled);
    });
    //return the first in the array
    return smil.pop();
}

有没有办法返回smilp.playlist中对象的id,或者我需要再次重写应用程序的很大一部分吗?

最佳答案

你可以这样做:

function getclosest(closest, element, index, array){
  if((time.getTime()-gettime(element.scheduled).getTime()) < (time.getTime()-gettime(closest.scheduled).getTime()) ) 
  return index;
  else
  return closest;  
}

smil.reduce(getclosest);

关于javascript - 查找具有较高项但低于限制的对象的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19301989/

相关文章:

javascript - 鸡尾酒配方数据可视化

javascript - Reactjs 将 key prop 分配给数组渲染组件

javascript - JavaScript 可以访问 &lt;script src =""> 元素的源代码吗?

javascript - 在 observableArray Knockout JS 中切换值?

php - 如何在PHP中动态创建对象数组

java - 将 Java int[][] 的神秘 bytea 表示形式转换回数组(Hibernate)

java - 将 CSV 文件导入二维字符串数组

javascript正则表达式单行

Javascript 对象路由映射

node.js - 在 TypeScript 中使用 process.env