0

I have an array of objects where I need to find closest lower value from that array based on some value or current value in angular 6, I have already tried but its showing undefined.

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);
  }
}
Saksham
  • 9,037
  • 7
  • 45
  • 73
carreankush
  • 621
  • 2
  • 9
  • 32
  • possible duplicate of [get the closest number out of array](https://stackoverflow.com/questions/8584902/get-closest-number-out-of-array) – mkamranhamid May 26 '19 at 09:33

5 Answers5

0

You have id in your array so this -

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

will not be undefined

jone
  • 1
  • 3
0

Change your function to:

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

}

Baruch Gans
  • 1,415
  • 1
  • 10
  • 21
0

You could find the nearest closet number as below

let arr = [
    { "id" : 1 },
    { "id" : 3 },
    { "id" : 5 }
];

let referenceNumber = 4;

let nearestLowest = arr.reduce((acc, val) => {
    if(val['id'] < referenceNumber && val['id'] > acc)
        acc = val['id'];
    return acc;
}, Math.max());

console.log(nearestLowest);
Saksham
  • 9,037
  • 7
  • 45
  • 73
0

Try this one.

  getPrev(){
     this.currentVal = 5;
     this.arrayVal= this.array; 
     let number = this.arrayVal.reduce((prev, current) => {
       return (Math.abs(current.id - this.currentVal) < Math.abs(prev.id - this.currentVal) ? current : prev);
     })
     console.log(number.id);
  }

Stackblitz

Sudarshana Dayananda
  • 5,165
  • 2
  • 23
  • 45
0

If your ids can be negative numbers, you can go with this:

getClosestLowerIdElement(value: number, array: Array<{[key: string]: number}>) {
    const v = {id: value};
    return array.reduce((acc, a) => acc = (
        (acc.id === undefined || Math.abs(v.id - a.id) < Math.abs(v.id - acc.id) || 
            acc.id > v.id) && a.id < v.id) ? a : acc, {id: undefined});
  }

And you can use it like this:

idArray = [{id: 1}, {id: -30}, {id: -5}, {id: 7}, {id: 9}, {id: 11}, {id: 21}];

...

console.log(this.getClosestLowerIdElement(0, this.idArray)); // prints {id: -5}

If there's no number lower than the value passed to the getClosestLowerIdElement method, you'll get {id: undefined}

See the demo on Stackblitz

julianobrasil
  • 8,954
  • 2
  • 33
  • 55