【问题标题】:Filter through array and find index for splice通过数组过滤并找到拼接的索引
【发布时间】:2017-07-14 06:45:57
【问题描述】:

我正在寻找筛选对象数组并找到匹配对象日期的索引或最接近的日期以在之后插入新对象。

let expenseIndex = tempArray.findIndex((a: any) => a.Date <= expense.Date);
tempArray.splice(expenseIndex, 0, expense);

&lt;= 运算符在这里似乎不起作用。如果我执行== 并找到匹配日期的费用,我会返回索引,但是当没有匹配时,我会得到0-1

【问题讨论】:

    标签: javascript arrays sorting angular typescript


    【解决方案1】:

    angular 在使用*ngFor 指令时提供索引。

    你可以得到当前的索引,如下图所示

    <div *ngFor="let item of items; let i = index;" 
         (click)="doSomethingWithIndex(i)">
      {{item.title}}
    </div>
    

    【讨论】:

    • 问题指出我需要在数组中插入一个“新”对象。您的示例适用于现有对象。还是谢谢
    【解决方案2】:

    试试这个(假设临时数组是按日期排序的):

    temp = temp
      .filter(v => v.Date <= exp.Date)
      .concat(exp, array.filter(v => v.Date > exp.Date))
    

    【讨论】:

      猜你喜欢
      • 2018-12-24
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多