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

不羁的心 提交于 2020-01-17 02:54:22

问题


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?

When I'm attempting to do so, it keeps telling me that the variable (in this case, students) is undefined.

When I use the built-in sort function, it works perfectly. However, this is a school assignment and I HAVE to show the breakdown of the quicksort function.

Here is the code I am using:

        function swap(student, firstIndex, secondIndex){
            var temp = student[firstIndex];
            student[firstIndex] = student[secondIndex];
            student[secondIndex] = temp;
        }

        function partition(student, left, right) {

            var pivot   = student[Math.floor((right + left) / 2)],
                i       = left,
                j       = right;


            while (i <= j) {

                while (student[i] < pivot) {
                    i++;
                }

                while (student[j] > pivot) {
                    j--;
                }

                if (i <= j) {
                    swap(student, i, j);
                    i++;
                    j--;
                }
            }

            return i;
        }

        function quickSort(student, left, right) {

            var index;

            if (student.length > 1) {

                left = typeof left != "number" ? 0 : left;
                right = typeof right != "number" ? student.length - 1 : right;

                index = partition(student, left, right);
                if (left < index - 1) {
                    quickSort(student, left, index - 1);
                }

                if (index < right) {
                    quickSort(student, index, right);
                }

            }

            return student;
        }

    var studentNumbersArray = []

    var randomArray = [];

    for (i = 0; i < studentsArray.length; i++) { 
        studentNumbersArray.push(studentsArray[i].studentNumber);              
    }


    function sortStudentNumbers() {    
        var student = studentNumbersArray.name; // <-- THIS IS WHERE I AM GETTING ERROR
        quickSort(student);
        var updatedStudentArray = JSON.stringify(studentsArray);
        localStorage.setItem("students", updatedStudentArray); 
        location.reload();
    }

回答1:


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.




回答2:


You cannot use a variable defined inside a function, in another function. Every function has its own scope, and in order to carry data between functions (inside the variables) you have to create a variable in the upper (global) scope. That means, you have to create the student and updatedStudentArray outside of the functions and use them without declaring in the functions (sortStudentNumbers() in this case)

var student;
var updatedStudentArray;

function swap(student, firstIndex, secondIndex){
    var temp = student[firstIndex];
    student[firstIndex] = student[secondIndex];
    student[secondIndex] = temp;
}

// ..................................
// ------ removed for clearity
// ..................................

function sortStudentNumbers() {    
    student = studentNumbersArray.name; // <-- THIS IS WHERE I AM GETTING ERROR
    quickSort(student);
    updatedStudentArray = JSON.stringify(studentsArray);
    localStorage.setItem("students", updatedStudentArray); 
    location.reload();
}

These the mistakes I found. But still, when I execute this code I get a studentsArray is not defined error on the console. Where is your studentsArray? If you have it somewhere, then it should all work now.

EDIT:

After you created the second question, I had a quick chance to have a look at your modified code. Don't forget to update your question here.

My Answer to your modified code: You have to set a "student" key in localStorage first, in order to use getItem() for it. You don't have anything in the localStorage, that is why your variable is not filled when you try to get the data from there. Thus, you are getting the error "Cannot read property 'studentNumber' of null".



来源:https://stackoverflow.com/questions/29967481/is-it-possible-to-quicksort-objects-in-an-array-based-on-a-property-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!