0

I wrote generic function for sorting array in typescript

export function sortArray(incomingArray: any[], sortField: string = '', sortOrder: string = 'asc'): any[] {
  if (!sortField) {
    return incomingArray;
  }

  let result: any[] = [];
  result = incomingArray.sort((a, b) => {
    let testData = a.ohlc['priceInUsd'];

    if (a[sortField] < b[sortField]) {
      return sortOrder === 'asc' ? -1 : 1;
    }

    if (a[sortField] > b[sortField]) {
      return sortOrder === 'asc' ? 1 : -1;
    }

    return 0;
  });
  return result;
}

Wokring perfectly fine till structure is inside one array. Problem is if I have more complex data like in photo and then "a[sortField]" doesn't wok well any more

enter image description here

How to chnage "a[sortField]" that will be more generic if I have more complex data and not need to write "a.x[sortField]"

senzacionale
  • 20,448
  • 67
  • 204
  • 316
  • 1
    This is not about sorting: you know about sorting. The question is how to access an attribute in a deep structure using a string path. – Amadan Feb 08 '21 at 21:31
  • 1
    Does this answer your question? [Access object child properties using a dot notation string](https://stackoverflow.com/questions/8051975/access-object-child-properties-using-a-dot-notation-string) – Amadan Feb 08 '21 at 21:31

0 Answers0