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);
}
3
  • Please provide enough data to duplicate your issues. This includes the actual data model(the arrays) you're not able to manipulate how you'd like. Commented Apr 12, 2019 at 16:01
  • I don't see any recursion here. Btw, why don't you use the sort method? Commented Apr 12, 2019 at 16:06
  • check this i hope its help full to you whitfin.io/sorting-object-recursively-node-jsjavascript Commented Apr 12, 2019 at 16:37

2 Answers 2

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) ;
}
Sign up to request clarification or add additional context in comments.

3 Comments

this won't work.
Just call the function it should work pass the array and the array keys without moficatios
You seem to assume that sort is stable (i.e. doesn't move already sorted items). This is normally not the case in javascript.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.