0

I have two arrays. One array is the array of items needing to be sorted. Another array is the keys (properties of that object) to sort by. I am wanting to have a function that sorts the array by each key given.

I have tried to loop over the keys array and pop each key off of the array and then sort but adding that key to the ternary I am using to sort the array has been giving me issues.

export function sortOrdersByKeys<T>(ordersArr: T[], sortByKeys: string[]): T[] 
{
    if (sortByKeys.length === 0) {
        return ordersArr;
    } else {
        const lastItem = sortByKeys.pop();
        return sortWithKey(ordersArr, lastItem);
    }
}

function sortWithKey(arr, key) {
    key = key[0];
    for (let i = 0; i < key.length(); i++) {

    }
    return arr.sort((a, b) => (a.key > b.key) ? 1 : -1);
}
JacobTStaggs
  • 107
  • 10

2 Answers2

0

This is a recursive function to sort based in the keys array. let me know if you need an explanation.

function sortWithKey(arr, keys) {
    const KEY = keys.pop();
    arr = arr.sort((a, b) => (a[KEY]> b[KEY]) ? 1 : -1);

    if(keys.legth <=0){
      return arr;
    } 
    return sortWithKey(arr, keys) ;
}
Abel Valdez
  • 2,368
  • 1
  • 16
  • 33
0

There are a few things going wrong here:

1) a.key will look up the "key" property of that object. You probably want a[key]

2) .length() is probably not a function

3) there is neither a recursive call nor a loop in your sortOrderByKeys

4) What is key = key[0]; supposed to do? To take only the first character of the key?

Your overall algorithm will also not work.

 array.sort(a).sort(b)

... will sort the array first on a and then on b. So it actually yields the same result as array.sort(b) ...

You rather have to sort once, and then when comparing two array elements a and b, then go over the keys until you find a difference.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151