首页 > 解决方案 > 如何在数组 angular 6 中找到最接近的较低值?

问题描述

我有一个对象数组,我需要根据角度 6 中的某个值或当前值从该数组中找到最接近的较低值,我已经尝试过,但它显示未定义。

app.component.html

<button (click) ="getPrev()">Previous Value</button>

app.component.ts

declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
    arrayVal:any;
    currentVal : any;
  title = 'projectchart';
  public array = [{"id":1},{"id":3},{"id":5}];


  getPrev(){
     this.currentVal = 5;
     this.arrayVal= this.array; 
     let number = this.arrayVal.reverse().find(e => e <= this.currentVal);
     console.log(number);
  }
}

标签: htmlangulartypescript

解决方案


你的数组中有 id 所以这个 -

 let number = this.arrayVal.reverse().find(e => e.id <= this.currentVal);

不会是未定义的


推荐阅读