方法1:
var datalist = [
{ type: 'Zach', value: 26, tag: 1 },
{ type: 'Tom', value: 29, tag: 2 },
{ type: 'Kate', value: 30, tag: 3 },
{ type: 'Gates', value: 31, tag: 4 },
{ type: 'Smith', value: 22, tag: 5 },
{ type: 'Jeny', value: 20, tag: 6 }];
datalist = datalist .sort((a, b) => a.id - b.id);
方法2:
var datalist = [
{ type: 'Zach', value: 26, tag: 1 },
{ type: 'Tom', value: 29, tag: 2 },
{ type: 'Kate', value: 30, tag: 3 },
{ type: 'Gates', value: 31, tag: 4 },
{ type: 'Smith', value: 22, tag: 5 },
{ type: 'Jeny', value: 20, tag: 6 }];
var result;
function compareFunc(propertytype) {
return function (obj1, obj2) {
var val1, val2;
val1 = obj1[propertytype];
val2 = obj2[propertytype];
if (val1 < val2) {
return -1;
} else if (val1 > val2) {
return 1;
} else {
return 0;
}
}
}
result = datalist.sort(compareFunc('value'));
console.log(result);
根据 对象数组某个key进行排序
最新推荐文章于 2023-05-02 16:17:43 发布