如何对数组的两种类型的值进行排序
How to sort 2 types of values for an array?
我正在尝试按字母顺序对项目进行排序。不过,我也想对项目类型进行排序。
例如:
我想要
type sortValue
blockItem a test1
blockItem a test2
blockItem b test3
imageItem a image
imageItem b image
imageItem c image
imageItem s image
textItem a text
textItem b text
textItem c text
我的代码会做这样的事情。
type sortValue
blockItem a test1
blockItem a test2
imageItem a image
textItem a text
blockItem b test3
imageItem b image
textItem b text
imageItem c image
textItem c text
imageItem s image
我的分拣功能
array contains type and sortvalue
array=array.sort(sortFunction);
function sortFunction(groupA, groupB) {
if (groupA.sortValue > groupB.sortValue) {
return 1;
} else if (groupA.sortValue < groupB.sortValue) {
return -1;
}
return 0;
}
它只对文本进行排序,而不对类型进行排序。我想知道是否有办法做到这一点。非常感谢!
使用第二个键来比较第一个键是否相等:
function sortFunction(a, b) {
if (a.key1 > b.key1) {
return +1;
} else if (a.key1 < b.key1) {
return -1;
} else if (a.key2 > b.key2) {
return +1;
} else if (a.key2 < b.key2) {
return -1;
} else
...
} else if (a.keyN > b.keyN) {
return +1;
} else if (a.keyN < b.keyN) {
return -1;
} else {
return 0;
}
}
或者,为了更好的可读性:
function sortFunction(a, b) {
if (a.key1 > b.key1) {
return +1;
} else if (a.key1 < b.key1) {
return -1;
}
if (a.key2 > b.key2) {
return +1;
} else if (a.key2 < b.key2) {
return -1;
}
...
if (a.keyN > b.keyN) {
return +1;
} else if (a.keyN < b.keyN) {
return -1;
}
return 0;
}
if (groupA.type == groupB.type) {
/* your code */
}
else if (groupA.type > groupB.type) {
return 1;
}
else if (groupA.type < groupB.type) {
return -1;
}
return 0;
相关文章:
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- jQuery dataTables基于类型的列筛选不起作用?Img alt过滤器/排序
- 在jQuery中对相同类型的多个元素进行排序
- 数组中的类型出现问题,并尝试将内容排序到表中
- MongoDB中的日期字段类型(并对其进行排序)
- 类型错误: 无法读取未定义的属性“排序级别”
- jQuery:根据类型对子项进行排序
- 使用jQuery中的整数字符串类型对数组进行排序
- 未捕获的类型错误:无法读取属性'排序方式'的未定义
- 类型错误:'未定义'在使用mongoDB排序运算符时不是函数
- 如何排序教科书的类型,颜色代码,或分类在bookweb使用html, Javascript, CSS或其他
- 使用javascript按不同类型排序
- 如何突出显示页面上数据排序类型的菜单项
- 方法Object.键对字符串类型的键id进行排序
- Backbone JS中的排序类型(动态)
- 在ExtJS中选择布尔字段排序的方向类型
- JavaScript对具有混合类型值的数组进行排序
- 如何对数组的两种类型的值进行排序
- angularjs ng表类型错误:无法读取属性'排序'的未定义
- 按钮单击后如何更改列排序类型?[jQuery,DataTables].