Created
July 15, 2021 03:19
-
-
Save chris-burkhardt/ee96e310f0530209c0395c7de07e8296 to your computer and use it in GitHub Desktop.
NodeJS QuickSort Descending
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var existingOrder = [{ | |
CreatedDate: "2021-07-12T03:49:57.000Z" | |
}, | |
{ | |
CreatedDate: "2021-07-13T09:25:23.000Z" | |
}, | |
{ | |
CreatedDate: "2021-07-18T04:52:41.000Z" | |
}, | |
{ | |
CreatedDate: "2021-07-14T05:27:32.000Z" | |
}, | |
{ | |
CreatedDate: "2021-07-10T08:18:57.000Z" | |
}, | |
{ | |
CreatedDate: "2021-07-14T08:19:42.000Z" | |
}, | |
{ | |
CreatedDate: "2021-07-16T08:37:15.000Z" | |
}, | |
] | |
/** | |
* Quicksort Algorithm to sort array in descending order. This was created | |
* because sort() is not stable in NodeJS v12 and returns inconsistant results. | |
* | |
* @param {*} array | |
* @returns DESC sorted array | |
*/ | |
function quickSortDesc(array) { | |
if (array.length < 2) { | |
return array; | |
} | |
const pivotItem = array[0]; | |
let lesserArray = []; | |
let greaterArray = []; | |
for (let i = 1; i < array.length; i++) { | |
if (array[i].CreatedDate < pivotItem.CreatedDate) { | |
greaterArray.push(array[i]); | |
} else { | |
lesserArray.push(array[i]); | |
} | |
} | |
return quickSortDesc(lesserArray).concat(pivotItem, quickSortDesc(greaterArray)); | |
} | |
console.log(quickSortDesc(existingOrder)); | |
Expected Output: | |
[{ | |
CreatedDate: "2021-07-18T04:52:41.000Z" | |
}, { | |
CreatedDate: "2021-07-16T08:37:15.000Z" | |
}, { | |
CreatedDate: "2021-07-14T08:19:42.000Z" | |
}, { | |
CreatedDate: "2021-07-14T05:27:32.000Z" | |
}, { | |
CreatedDate: "2021-07-13T09:25:23.000Z" | |
}, { | |
CreatedDate: "2021-07-12T03:49:57.000Z" | |
}, { | |
CreatedDate: "2021-07-10T08:18:57.000Z" | |
}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment