下划线多维排序
Underscore multidimensional sortBy
我有一个对象
[
{ "home1": { "mesafe":11 } },
{ "home2": { "mesafe": 6 } },
{ "home3": { "mesafe":42 } },
{ "home4": { "mesafe":23 } },
{ "home5": { "mesafe": 5 } }
]
我如何排序这个对象与mesafe
字段顺序ASC数字使用下划线?
你可以考虑
{
"home1": {
"mesafe":11
}
}
{
"home1": {
"mesafe":11
},
// fakes
"home2": {},
"home3": {}...
}
现在要排序的值可以描述为:
从subbobject中获取所有mesafe
属性的值并将它们相加(如果该属性存在)
所以你可以用_.reduce
来实现。
var list = [
{ "home1": { "mesafe":11 } },
{ "home2": { "mesafe": 6 } },
{ "home3": { "mesafe":42 } },
{ "home4": { "mesafe":23 } },
{ "home5": { "mesafe": 5 } }
];
var sortedList = _.sortBy(list, function(item) {
// For each item, we acts as there not only have one attribute "homex", but there's many other like "homey : {}".
var res = _.reduce(item, function(res, sub) {
// So we can the again use reduce to iterate through them, and add the value if mesafe exist.
return (sub.mesafe == null) ? res : res + sub.mesafe;
}, 0);
return res;
});
console.log(sortedList);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
您可以使用JavaScript Array sort()方法根据mesafe
字段的值对数组进行排序。
var data = [
{ "home1": { "mesafe":11 } },
{ "home2": { "mesafe": 6 } },
{ "home3": { "mesafe":42 } },
{ "home4": { "mesafe":23 } },
{ "home5": { "mesafe": 5 } }
];
// get the value from mesafe field
function getMesafeValue(a) {
for (var key in a) {
if (a.hasOwnProperty(key)) {
return a[key].mesafe;
}
}
}
// sort the array
data.sort(function(a, b) {
var v1 = getMesafeValue(a);
var v2 = getMesafeValue(b);
return v1 < v2 ? -1 : (v1 > v2 ? 1 : 0);
});
// print the array after sorting
for (var i = 0; i < data.length; i++) {
for (var key in data[i]) {
if (data[i].hasOwnProperty(key)) {
document.write(key + " -> " + data[i][key].mesafe + '<br/>');
}
}
}
相关文章:
- 如何使用下划线根据自定义排序顺序对对象数组进行排序
- 使用下划线排序依据对对象进行排序
- 使用下划线排序
- 如何使用下划线对以下数组进行排序
- 检查列表是否在javascript中使用下划线.js排序
- 按表示节号的字符串排序的下划线
- 在主动JS中使用下划线进行排序
- 带有下划线排序的对象排序的数组
- Javascript 下划线 - 按数组对象中的字段总和排序
- 如何使用下划线 js 对 JavaScript 对象进行排序
- 使用lodash/下划线聚合排序限制
- 使用下划线在javascript中重新排序对象
- 下划线:在数组'排序之后,如何保持数组的顺序
- 如何使用下划线对多个键进行排序
- 下划线多维排序
- 为什么javascript localeCompare在句号前排序下划线?
- 在javascript中使用函数或下划线排序
- 我怎么能做一个asc和desc排序使用下划线
- j查询或下划线 按范围文本对列表进行排序
- 用下划线对对象进行分组和排序