Is it possible to quicksort objects based on their keys in an array, using JavaScript?

前端 未结 2 1533
小蘑菇
小蘑菇 2021-01-27 10:48

To clarify a bit on the question, I have an array and within the array are a bunch of objects. Can I rearrange the objects in the array based on the key values of each object? <

2条回答
  •  囚心锁ツ
    2021-01-27 11:10

    After seeing several permutations of your code I think what you are trying to do needs to look a little something like this.

    quickSort(arrayToSort, attributeToSortOn, left, right) {
        ...
    }
    ...
    function partition(arrayToSort, attributeToSortOn, left, right) {
        var pivot = student[Math.floor((right + left) / 2)][attributeToSortOn]
        ...
        while (arrayToSort[i][attributeToSortOn] < pivot) {
        ...
    }
    ...
    quickSort(studentsArray, 'studentNumber');
    

    quickSort always needs the array to compare values at each position. You can't just pass studentsArray.studentNumber because the attribute to sort on is useless on it's own and the array has no knowledge of the types of object contained within it anyway.

提交回复
热议问题