作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我得到了一个对象数组
const users= [{
Location: {
label: "aa",
value: "aa"
},
Name: "test7"
id: "002"
},
Location: {
label: "aa",
value: "aa"
},
Name: "test4"
id: "003"
},
{
Location: {
label: "ss",
value: "ss"
},
Name: "test4"
id: "004"
}]
const dynamicSort = property => {
var sortOrder = 1;
if (property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function(a, b) {
var result;
if (property === "deviceLocation")
result =
a[property].label < b[property].label
? -1
: a[property].label > b[property].label
? 1
: 0;
else
result =
a[property] < b[property] ? -1 : a[property] > b[property] ? 1 : 0;
return result * sortOrder;
};
};
users.sort(dynamicSort("deviceLocation"))
const users= [{
Location: {
label: "aa",
value: "aa"
},
Name: "test4"
id: "003"
},
Location: {
label: "aa",
value: "aa"
},
Name: "test7"
id: "002"
},
{
Location: {
label: "ss",
value: "ss"
},
Name: "test4"
id: "004"
}]
最佳答案
首先,您应该在问题中使用 JSON 或 JavaScript 对象。
然后,您可以创建一个排序函数,该函数首先对用户所在位置的标签进行排序,然后是用户的姓名。
console.log(getUsers().sort(userComparator));
function userComparator(userA, userB) {
let diff = userA.Location.label.localeCompare(userB.Location.label);
return diff === 0 ? userA.Name.localeCompare(userB.Name) : diff;
}
function getUsers() {
return [{
"Location": {
"label": "colombo",
"value": "colombo"
},
"Name": "test7",
"id": "002"
}, {
"Location": {
"label": "jaffna",
"value": "jaffna"
},
"Name": "test4",
"id": "004"
}, {
"Location": {
"label": "colombo",
"value": "colombo"
},
"Name": "test4",
"id": "003"
}];
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
关于javascript - 如何对对象数组进行分组和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60455989/
我是一名优秀的程序员,十分优秀!