0

So I have a list of Items

const items = this.props.complex_object?.items;

And I would like to sort these items based on a key. I would naturally like to perform the following

const sortedItems = this.props.complex_object?.items.sort(
  (a, b) => a?.confidence > b?.confidence
);

Yet I am getting the following flow error.

Flow does not yet support method or property calls in optional chains.

Which somewhat makes sense because items is of the flow type ?Array<ItemType>. Given the conditional nature of the existence of Items, I have tried to check for null and undefined

var items = this.props.complex_object?.items;

if (items === null || items === undefined)
  items = [];

const sortedItems = items.sort((a, b) => a. confidence > b.confidence);

return (<Table items=sortedItems>);

Yet this doesn't alleviate the problem. Bottom line, how do I sort an array of optional objects?

Many Thanks in Advance

FinnM
  • 394
  • 1
  • 3
  • 17
  • 1
    You shouldn't use `>` operator in `compareFunction`: [Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?](https://stackoverflow.com/questions/24080785) – adiga Jul 02 '19 at 16:33
  • @adiga, good to know! – FinnM Jul 02 '19 at 17:23

1 Answers1

2

If you know that props.complex_object will always exist, you could do

var items = this.props.complex_object.items || [];

If items does not exist on your complex_object (undefined), or exists but has a value of undefined or null, then it will default it to the empty array.

adiga
  • 34,372
  • 9
  • 61
  • 83
Steve -Cutter- Blades
  • 5,057
  • 2
  • 26
  • 40
  • 2
    Piggybacking on this, if you don't know if `complex_object` will exist you can do `var items = (this.props.complex_object || {}).items || []` – hobberwickey Jul 02 '19 at 17:38