Javascript 按两个值排序,优先考虑其中之一
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4576714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort by two values prioritizing on one of them
提问by Dojie
How would I sort this data by count
and year
values in ascending order prioritizing on the count
value?
我将如何按值按升序对这些数据进行排序,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' },
];
回答by cdhowie
data.sort(function (x, y) {
var n = x.count - y.count;
if (n !== 0) {
return n;
}
return x.year - y.year;
});
回答by RobG
A simple solution is:
一个简单的解决方案是:
data.sort(function (a, b) {
return a.count - b.count || a.year - b.year;
});
This works because if countis different, then the sort is based on that. If countis the same, the first expression returns 0 which converts to falseand the result of the second expression is used (i.e. the sort is based on year).
这是有效的,因为如果计数不同,则排序基于此。如果count相同,则第一个表达式返回 0 并转换为false并使用第二个表达式的结果(即排序基于year)。
回答by PleaseStand
You can use JavaScript's .sort()
array method (try it out):
你可以使用 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;
});
Note: This changes the original array. If you need to make a copy first, you can do so:
注意:这会更改原始数组。如果您需要先制作副本,您可以这样做:
var dataCopy = data.slice(0);
回答by 19WAS85
Based on great @RobG solution, this is a generic function to sort by multiple different properties, using a JS2015 tricky on map + find
:
基于伟大的@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)
Also, if you prefer, a traditional JS version (use with caution due to find compatibilityin old browsers):
此外,如果您愿意,可以使用传统的 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;
});
});
};
回答by paul
you have to work out this problem like this way
你必须像这样解决这个问题
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;
}
};
};
};
e.g : data.sort(customSort('year', customSort('count')));
例如: data.sort(customSort('year', customSort('count')));
回答by abs
user this where 'count'-> first priority and 'year'-> second priority
user this where 'count'-> first priority and 'year'-> second priority
data.sort(function(a,b){
return a['count']<b['count']?-1:(a['count']>b['count']?1:(a['year']<b['year']?-1:1));
});
回答by Boris Yakubchik
If you are looking to sort stringsin alphabetical order rather than numbers, here's a sample problem and its solution.
如果您想按字母顺序而不是数字对字符串进行排序,这里有一个示例问题及其解决方案。
Example Problem:Array of arrays (finalArray) with first entry a folder path and second entry the file name; sort so that array is arranged by folder first, and within identical folders, by file name.
示例问题:数组(finalArray),第一个条目是文件夹路径,第二个条目是文件名;排序,以便数组首先按文件夹排列,然后在相同的文件夹中按文件名排列。
E.g. after sorting you expect:
例如在排序后你期望:
[['folder1', 'abc.jpg'],
['folder1', 'xyz.jpg'],
['folder2', 'def.jpg'],
['folder2', 'pqr.jpg']]
Refer to Array.prototype.sort() - compareFunction
参考Array.prototype.sort() - compareFunction
finalArray.sort((x: any, y: any): number => {
const folder1: string = x[0].toLowerCase();
const folder2: string = y[0].toLowerCase();
const file1: string = x[1].toLowerCase();
const file2: string = y[1].toLowerCase();
if (folder1 > folder2) {
return 1;
} else if (folder1 === folder2 && file1 > file2) {
return 1;
} else if (folder1 === folder2 && file1 === file2) {
return 0;
} else if (folder1 === folder2 && file1 < file2) {
return -1;
} else if (folder1 < folder2) {
return -1;
}
});
Keep in mind, "Z" comes before "a" (capitals first according to Unicode code point) which is why I have toLowerCase(). The problem the above implementation does not solve is that "10abc" will come before "9abc".
请记住,“Z”在“a”之前(根据Unicode 代码点大写),这就是为什么我必须使用toLowerCase()。上述实现没有解决的问题是“10abc”会出现在“9abc”之前。