[英]sort Javascript object by value, returns wrong result
I create the publicPostContent array with a Promise. 我用Promise创建publicPostContent数组。 Once that is finished creating.
一旦完成创建。 I see I have an array of 3 Javascript objects which I am trying to sort on the value of Grade which is for instance: 17.23949/ 25.50033/ 40.23245
我看到我有3个Javascript对象的数组,我正在尝试按Grade的值进行排序,例如:17.23949 / 25.50033 / 40.23245
I use the compare function as below, however this doesn't seem to work at all, I used different compare functions. 我使用如下比较函数,但是这似乎根本不起作用,我使用了不同的比较函数。 But to no result.
但是没有结果。 I am starting to think my javascript Object is in the incorrect format?
我开始认为我的javascript对象格式不正确? I get no errors, but the sorting seems to give a different result each time I refresh.
我没有收到任何错误,但是每次刷新时,排序似乎都给出了不同的结果。
the console.log(a) returns nothing. console.log(a)不返回任何内容。
this.publicPostContent[i] = {"_id": key._id,"timePast" :
this.timePastPublic, "grade": this.publicPostGrade[i]}
this.publicPostContent.sort(this.compareValues('grade'));
compareValues(key, order = 'asc') {
return function(a, b) {
if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
// property doesn't exist on either object
return 0;
}
console.log(a)
const varA = (typeof a[key] === 'string') ?
a[key].toUpperCase() : a[key];
const varB = (typeof b[key] === 'string') ?
b[key].toUpperCase() : b[key];
console.log(varA)
let comparison = 0;
if (varA > varB) {
comparison = 1;
} else if (varA < varB) {
comparison = -1;
}
return (
(order == 'desc') ? (comparison * -1) : comparison
);
};
}
You can try this code to sort by key 您可以尝试此代码按键排序
var array =[{"grade":50.23949},{"grade":17.23949} ,{"grade":25.50033},{"grade":40.23245}]; function sortByKey(unSortArray,key) { return unSortArray.sort(function(first, second) { if(!first.hasOwnProperty(key) || !first.hasOwnProperty(key)) { // property doesn't exist on either object return 0; } if (first[key] == second[key]) return 0; if (first[key] < second[key]) return -1; else return 1; }); } var sortArray = sortByKey(array,"grade"); console.log(sortArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.