Home > Software design >  How to filter array of custom type in typescript
How to filter array of custom type in typescript

Time:02-18

i have an array of devices that look like this.


export interface Device {
    id:                      Number;
    tracker_status?:         Trackerstatus;
}


export interface Trackerstatus {
    last_update?: Date;
    battery_low?: any;
}

applying a filter like

function filterDevices(device: any) {
    if (device.id == 5){
        return true;
    }else{
        return false;
    }
}

works perfectly fine.

however what i am trying to do is

function filterDevices(device: any) {
  if (device.tracker_status.battery_low == "true"){
    return true;
  }else{
  return false;
  }
}

this just returns an empty list with no error messages. what am i doing wrong?

the goal is to show the filtered data in an angular table. i am using the filter like this

devices: Device[] = data.filter(filterDevices);

CodePudding user response:

You're checking against the string "true". Did you check if the device.tracker_status.battery_low property is a boolean or a string?

Note that both true == "true" and false == "true" would return false.

console.log(true == "true");
console.log(false == "true");

I'd suggest the following

function filterDevices(device: any) {
  return !!(device?.tracker_status?.battery_low);
}
  1. More about the double-negation operator !! here.
  2. More about the optional-chaining operator ?. here.

CodePudding user response:

found the solution. forgot to check console logs

simply checking if tracker status is not null since not every device has it solved the problem.

  • Related