对具有点分隔数字的属性的对象数组进行排序
Sort array of objects with property having dot separated number
我有这样的对象数组
var arr = [{
"id": "1",
"Title": "Object1",
"SectionId": "1.2.1"
}, {
"id": "2",
"Title": "Object2",
"SectionId": "1.1.2"
}, {
"id": "3",
"Title": "Object3",
"SectionId": "1.0.1"
}, {
"id": "4",
"Title": "Object4",
"SectionId": "1"
}];
sectionId
有数字分隔的点。如何根据 sectionId
属性按升序或降序对数组进行排序?
灵感来自使用地图排序
function customSort(d, order) {
var sort = {
asc: function (a, b) {
var l = 0, m = Math.min(a.value.length, b.value.length);
while (l < m && a.value[l] === b.value[l]) {
l++;
}
return l === m ? a.value.length - b.value.length : a.value[l] - b.value[l];
},
desc: function (a, b) {
return sort.asc(b, a);
}
},
// temporary array holds objects with position and sort-value
mapped = d.map(function (el, i) {
return { index: i, value: el.SectionId.split('.').map(Number) };
});
// sorting the mapped array containing the reduced values
mapped.sort(sort[order] || sort.asc);
// container for the resulting order
return mapped.map(function (el) {
return d[el.index];
});
}
var arr = [{ "id": "1", "Title": "Object1", "SectionId": "1.2.1" }, { "id": "2", "Title": "Object2", "SectionId": "1.1.2" }, { "id": "3", "Title": "Object3", "SectionId": "1.0.1" }, { "id": "4", "Title": "Object4", "SectionId": "1.1.10" }, { "id": "5", "Title": "Object5", "SectionId": "1" }];
document.write('<pre>sorted array asc ' + JSON.stringify(customSort(arr), 0, 4) + '</pre>');
document.write('<pre>sorted array desc ' + JSON.stringify(customSort(arr, 'desc'), 0, 4) + '</pre>');
document.write('<pre>original array ' + JSON.stringify(arr, 0, 4) + '</pre>');
var sort = function(isAsc) {
return function(a, b) {
var x = a.SectionId.split('.').map(Number)
var y = b.SectionId.split('.').map(Number)
for (var i = 0; i < 3; i++) {
if (x[i] > y[i]) return isAsc ? 1 : -1;
if (x[i] < y[i]) return isAsc ? -1 : 1;
if (!isNaN(x[i]) && isNaN(y[i])) return isAsc ? 1 : -1;
if (isNaN(x[i]) && !isNaN(y[i])) return isAsc ? -1 : 1;
}
return 0;
}
}
var acs = sort(true)
var desc = sort()
arr.sort(acs)
arr.sort(desc)
var arr = [{
"id": "1",
"Title": "Object1",
"SectionId": "1.2.1"
}, {
"id": "2",
"Title": "Object2",
"SectionId": "1.1.2"
}, {
"id": "3",
"Title": "Object3",
"SectionId": "1.0.1"
}, {
"id": "4",
"Title": "Object4",
"SectionId": "1"
}];
const result = arr.sort((a, b) => (a.SectionId > b.SectionId) ? 1 : -1);
相关文章:
- 将数组对象传递到struts2中的操作类
- 如何使用jquery返回php-json数组对象
- 从其名称获取javascript数组对象
- 值未与数组对象绑定
- 如何按数组/对象值的倍数过滤对象数组
- 在表中显示数组对象
- 在数组对象中分组
- 将第二个或多个数组推送到数组对象 AngularJS 中
- 重新排列 JavaScript 数组/对象
- 键上的javascript数组对象过滤器
- handontable:在不更改数据数组/对象的情况下隐藏某些列
- 用于跟踪购物车可用性的Javascript数组/对象/哈希表
- 重建有角度的java脚本数组对象
- 对JSON数组对象进行排序
- 连接与数组对象相关的文本:方式和位置
- 哪些浏览器和版本支持将常见的类数组对象直接传递到fn.apply()
- 如何使用Handlebars循环数组对象和模板
- 是否可以引用JS数组/对象中的另一个元素
- Javascript中的名称索引-数组/对象
- 数组长度不等于数组对象