JS 数组中根据某个字段进行排序
const arr = [
{ name: "崔喻琪", age: 32 },
{ name: " 王忱景", age: 18 },
{ name: " 房真睿", age: 27 },
{ name: "姬泉孝", age: 20 },
{ name: "余嘉芳", age: 16 },
{ name: "孙平卉", age: 23 },
];
console.log(this.abilitySort(arr, "age", true));
/** 根据传入的字段进行排序
* @param arr 需要排序的数组
* @param property 排序的字段
* @param desc true.升序 false.降序
* @returns {*} 排好序后的数组
*/
abilitySort(arr, property, desc) {
return arr.sort(function (a, b) {
const val1 = a[property];
const val2 = b[property];
if (desc) {
return val1 - val2; // 升序排列
} else {
return val2 - val1; // 降序排列
}
});
}
JS 数组中根据某个字段进行分组
const arr = [
{ id: "1001", name: "崔喻琪", age: 32 },
{ id: "1001", name: " 王忱景", age: 18 },
{ id: "1001", name: " 房真睿", age: 27 },
{ id: "1002", name: "姬泉孝", age: 20 },
{ id: "1002", name: "余嘉芳", age: 16 },
{ id: "1003", name: "孙平卉", age: 23 },
];
console.log(this.abilitySort(arr, "id"));
/** 根据传入的字段进行分组
* @param arr 需要分组的数组
* @param property 分组的字段
* @returns {*[]} 已分好组的数组
*/
abilitySort(arr, property) {
let map = {};
for (let i = 0; i < arr.length; i++) {
const ai = arr[i];
if (!map[ai[property]]) map[ai[property]] = [ai];
else map[ai[property]].push(ai);
}
let res = [];
Object.keys(map).forEach((key) => {
res.push({ [property]: key, data: map[key] });
});
return res;
}