Doj*_*jie 48 javascript sorting
我如何按值优先排序这些数据count并按year升序排列count值?
//sort this
var data = [
{ count: '12', year: '1956' },
{ count: '1', year: '1971' },
{ count: '33', year: '1989' },
{ count: '33', year: '1988' }
];
//to get this
var data = [
{ count: '1', year: '1971' },
{ count: '12', year: '1956' },
{ count: '33', year: '1988' },
{ count: '33', year: '1989' },
];
Run Code Online (Sandbox Code Playgroud)
cdh*_*wie 72
data.sort(function (x, y) {
var n = x.count - y.count;
if (n !== 0) {
return n;
}
return x.year - y.year;
});
Run Code Online (Sandbox Code Playgroud)
Rob*_*obG 52
一个简单的解决方案是
data.sort(function (a, b) {
return a.count - b.count || a.year - b.year;
});
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为如果count不同,则排序基于此.如果count相同,则第一个表达式返回0,转换为false,并使用第二个表达式的结果(即排序基于年份).
Ple*_*and 13
你可以使用JavaScript的.sort()数组方法(试一试):
data.sort(function(a, b) {
// Sort by count
var dCount = a.count - b.count;
if(dCount) return dCount;
// If there is a tie, sort by year
var dYear = a.year - b.year;
return dYear;
});
Run Code Online (Sandbox Code Playgroud)
注意:这会更改原始数组.如果您需要先制作副本,可以这样做:
var dataCopy = data.slice(0);
Run Code Online (Sandbox Code Playgroud)
基于优秀的@RobG 解决方案,这是一个通用函数,可以使用JS2015棘手的多种不同属性进行排序map + find:
let sortBy = (p, a) => a.sort((i, j) => p.map(v => i[v] - j[v]).find(r => r))
sortBy(['count', 'year'], data)
Run Code Online (Sandbox Code Playgroud)
此外,如果您愿意,还可以使用传统的JS版本(由于在旧版浏览器中找到兼容性,请谨慎使用):
var sortBy = function (properties, targetArray) {
targetArray.sort(function (i, j) {
return properties.map(function (prop) {
return i[prop] - j[prop];
}).find(function (result) {
return result;
});
});
};
Run Code Online (Sandbox Code Playgroud)
你必须像这样解决这个问题
var customSort = function(name, type){
return function(o, p){
var a, b;
if(o && p && typeof o === 'object' && typeof p === 'object'){
a = o[name];
b = p[name];
if(a === b){
return typeof type === 'function' ? type(o, p) : o;
}
if(typeof a=== typeof b){
return a < b ? -1 : 1;
}
return typeof a < typeof b ? -1 : 1;
}
};
Run Code Online (Sandbox Code Playgroud)
};
例如:data.sort(customSort('year',customSort('count')));
| 归档时间: |
|
| 查看次数: |
35395 次 |
| 最近记录: |