【发布时间】:2016-01-31 06:02:57
【问题描述】:
您好,我正在尝试通过其 ID 对 localStorage 中的一些数据进行排序。
数据的格式是这样的: {"品牌":"讴歌","型号":"选择您的型号","年龄":"1998","KM":"10","姓名":"Harry","ContactInfo":"123456677" }
我想按 KM 值的从低到高的顺序排序。
我的本地存储密钥已注册,这是我正在使用的代码:
function Qsort() {
var mymain = JSON.parse(localStorage.getItem("register"));
var result = quicksort(mymain, 0, mymain.length - 1);
// the following line fo code shows the final result of the sorted numbers or strings
console.log(mymain);
console.log(quicksort(mymain, 0, mymain.length - 1));
return result;
}
function quicksort(mymain, left, right) {
var index;
// checks if there are more than one numbers
if (mymain.length > 1) {
// partition will find a pivot then split leist in two either left of right.
// Left list contains everything that is smaller than the pivot and the right contians everythign larger than pivot
index = partition(mymain, left, right);
// will treat left side aas a new problem and will then run the sort
if (left < index - 1){
quicksort(mymain, left, index - 1)
}
// will treat right side as a new problem and will then run the sort
if (index < right) {
quicksort(mymain, index, right)
}
}
return mymain
}
// Divides the whole function
function partition(mymain, left, right) {
var pivot = mymain[Math.floor((right + left) / 2)],
i = left,
j = right;
while (i <= j) {
while (mymain[i] < pivot) {
i++;
}
while (mymain[j] > pivot) {
j--;
}
if (i <= j) {
swap(mymain, i, j);
i++;
j--;
}
}
return i;
}
// swaps the values based on how high or low the number is
function swap(mymain, firstIndex, secondIndex) {
var temp = mymain[firstIndex];
mymain[firstIndex] = mymain[secondIndex];
mymain[secondIndex] = temp;
}
我应该如何处理var mymain 部分,以便它只获取 KM 下定义的值。
【问题讨论】:
-
除非它的集合太大......你真的可能想尝试类似:
function order(x, key) { return x.sort(function(a,b) { return a[key] - b[key] }) }
标签: javascript local-storage quicksort