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

前端 未结 2 1534
小蘑菇
小蘑菇 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:07

    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".

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题