所以我之前发布了这个问题,但是我复制了错误的代码。这是您感兴趣的链接:Is it possible to quicksort objects based on their keys in an array, using JavaScript?
我有一个包含大量对象的数组。我要做的是根据特定属性(所有对象都拥有)重新排序数组。
所以这是我的代码:
studentsArray = [];
studentsArray = JSON.parse(localStorage.getItem("students"));
console.log(studentsArray);
function swap(qStudent, firstIndex, secondIndex){
var temp = qStudent[firstIndex];
qStudent[firstIndex] = qStudent[secondIndex];
qStudent[secondIndex] = temp;
}
function partition(qStudent, left, right) {
var pivot = qStudent[Math.floor((right + left) / 2)],
i = left,
j = right;
while (i <= j) {
while (qStudent[i] < pivot) {
i++;
}
while (qStudent[j] > pivot) {
j--;
}
if (i <= j) {
swap(qStudent, i, j);
i++;
j--;
}
}
return i;
}
function quickSort(qStudent, left, right) {
var index;
if (qStudent.length > 1) {
left = typeof left != "number" ? 0 : left;
right = typeof right != "number" ? qStudent.length - 1 : right;
index = partition(qStudent, left, right);
if (left < index - 1) {
quickSort(qStudent, left, index - 1);
}
if (index < right) {
quickSort(qStudent, index, right);
}
}
return qStudent;
}
console.log(studentsArray.studentNumber); // <-- THIS RETURNS undefined IN CONSOLE
var students;
var updatedStudentArray;
var qStudent;
function sortStudentNumbers() {
var qStudent = studentsArray.studentNumber;
quickSort(qStudent);
var updatedStudentArray = JSON.stringify(studentsArray);
localStorage.setItem("students", updatedStudentArray);
location.reload();
}
在我的本地存储中,它看起来像这样:
Key: students
Value: [{"studentNumber":"123456","name":"Elisa Woman","presentNumber":0,"lateNumber":0,"absentNumber":0},{"studentNumber":"661211","name":"First Last","presentNumber":0,"lateNumber":0,"absentNumber":0},{"studentNumber":"941035","name":"Another Person","presentNumber":0,"lateNumber":0,"absentNumber":0}]
每当我尝试快速输入studentArrays.studentNumber时,Google Chrome(开发人员工具)会给我一个错误,指出无法读取未定义的长度。
当我使用内置排序功能时,它完美地运行,但不幸的是这是一个学校项目所以我必须打破快速排序功能。我的代码有什么问题吗?关于如何解决这个问题的任何建议?
提前致谢!