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

前端 未结 2 1538
小蘑菇
小蘑菇 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".

提交回复
热议问题