I'm building a flash card app that will need to be able to alphabetically sort lists of decks, cards, etc. and I want to use one quicksort function for all of them rather than building a sort function to each. I figured I'd just pass the array of objects and the key that holds the content to be sorted by as arguments to the function but it's not sorting properly.
The code below that I had written to sort cards alphabetically by the card object's 'question' property works:
const pivot = (arr, start) => {
let pivotVal = arr[start]['question'].toUpperCase();
let swapIdx = start;
for(let a = start + 1; a < arr.length; a++){
if(pivotVal > arr[a]['question'].toUpperCase()){
swapIdx++;
swap(arr, swapIdx, a);
}
};
swap(arr, start, swapIdx);
return swapIdx;
}
const alphabetize = (arr, start = 0, end = arr.length - 1) => {
if(start < end){
let pivotIdx = pivot(arr, start);
alphabetize(arr, start, pivotIdx - 1)
alphabetize(arr, pivotIdx + 1);
}
return arr;
}
setCards(alphabetize(newCards, 0, cards.length - 1)); //(useState hook)
But then trying to make it universally usable by passing a key as an argument with the code below does not:
const pivot = (arr, start, comparand) => {
let pivotVal = arr[start][`${comparand}`].toUpperCase();
let swapIdx = start;
for(let a = start + 1; a < arr.length; a++){
if(pivotVal > arr[a][`${comparand}`].toUpperCase()){
swapIdx++;
swap(arr, swapIdx, a);
}
};
swap(arr, start, swapIdx);
return swapIdx;
}
const alphabetize = (arr, start = 0, end = arr.length - 1, comparand) => {
if(start < end){
let pivotIdx = pivot(arr, start, comparand);
alphabetize(arr, start, pivotIdx - 1, comparand)
alphabetize(arr, pivotIdx + 1, comparand);
}
return arr;
}
setCards(alphabetize(newCards, 0, cards.length - 1, 'question')); //(useState hook)
It doesn't break or anything; it's just not truly alphabetizing the list. I'd read the answers to this post In JavaScript how can I use a function parameter as the key to an object? and it seemed like using template literals for dynamic keys should work. Any ideas what's wrong with the second code block?