-1

I read about ternary operators but both the filter data and sort data is still kind of confusing. I might be understanding it wrong but it seems to be a sort of IF.

This is from the ZORRO framework. Section - Filter and Sorter

https://ng.ant.design/components/table/en#components-table-demo-virtual

search(): void {
    /** filter data **/
    const filterFunc = (item: { name: string; age: number; address: string }) =>
      (this.searchAddress ? item.address.indexOf(this.searchAddress) !== -1 : true) &&
      (this.listOfSearchName.length ? this.listOfSearchName.some(name => item.name.indexOf(name) !== -1) : true);
    const data = this.listOfData.filter(item => filterFunc(item));
    console.log(data);
    /** sort data **/
    if (this.sortName && this.sortValue) {
      this.listOfDisplayData = data.sort((a, b) =>
        this.sortValue === 'ascend'
          ? a[this.sortName!] > b[this.sortName!]
            ? 1
            : -1
          : b[this.sortName!] > a[this.sortName!]
          ? 1
          : -1
      );
    } else {
      this.listOfDisplayData = data;
    }
  }

Matt Tester
  • 3,865
  • 3
  • 27
  • 31
Rod Flores
  • 45
  • 3
  • 1
    The code contains a chained [conditional (or ternary) operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) – jmoerdyk Mar 26 '19 at 21:28

2 Answers2

2

It is confusing looking code (and so not recommended), but it is a series of ternary operators. This is exactly the same as an if/else statement, just written in a short-hand way.

So it looks confusing because the if (the ?) and else (the :) of the first ternary operator is itself another ternary operator!

 return this.sortValue === 'ascend'
          ? a[this.sortName!] > b[this.sortName!]
            ? 1
            : -1
          : b[this.sortName!] > a[this.sortName!]
          ? 1
          : -1

Is the same as:

if (this.sortValue === 'ascend') {
  if(a[this.sortName!] > b[this.sortName!]) {
    return 1;
  } else {
    return -1;
  }
} else {
  if (b[this.sortName!] > a[this.sortName!]) {
    return 1;
  } else {
    return -1;
  }
}
Matt Tester
  • 3,865
  • 3
  • 27
  • 31
0

It is known as Conditional Operator (also called ternary operator).

It has the form of: condition ? value-if-true : value-if-false Think of the ? as "then" and : as "else".

For example,

return this.sortValue === 'ascend'
          ? ( a[this.sortName!] > b[this.sortName!] ? 1 : -1 )
          : (b[this.sortName!] > a[this.sortName!] ? 1 : -1)
Seba Cherian
  • 1,612
  • 3
  • 17