我有一个对象数组,我必须遍历这些对象并按属性名称“tagColor”对重复值进行分组,然后我需要按名称对分组的对象进行排序。我实现了按颜色排序的第一步,现在我只需要按名称对那些组进行排序,以 angular 4 typescript 实现这一点
这里是数组列表
tags = [
{
"tagType": {
"name": "a",
"tagColor": "#0000FF"
}
},
{
"tagType": {
"name": "a",
"tagColor": "#FF0000"
}
},
{
"tagType": {
"name": "c",
"tagColor": "#FF0000",
}
},
{
"tagType": {
"name": "b",
"tagColor": "#FF0000",
}
},
{
"tagType": {
"name": "b",
"tagColor": "#0000FF",
}
}
]
按 tagColor 排序的函数:
tags.sort((a, b) => a.tagType.tagColor.localeCompare(b.tagType.tagColor));
这仅按颜色分组,但如何按字母顺序对这些组进行排序?
最佳答案
您可以使用单个排序调用,如果比较标签的结果为 0,您可以按名称进行比较:
tags.sort((a, b) => {
let result = b.tagType.tagColor.localeCompare(a.tagType.tagColor);
if(result == 0) {
return a.tagType.name.localeCompare(b.tagType.name);
}
return result;
});
或者更简洁但可读性较差的版本:
tags.sort((a, b) =>
b.tagType.tagColor.localeCompare(a.tagType.tagColor) // if this is 0 (aka falsy) return the other value
|| a.tagType.name.localeCompare(b.tagType.name));
关于javascript - 将 javascript 数组中的重复值分组在一起,然后按值名称升序对这些组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51619223/