Javascript 如何按日期属性对数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10123953/
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
How to sort an array by a date property
提问by ryandlf
Say I have an array of a few objects:
假设我有几个对象的数组:
var array = [{id: 1, date: Mar 12 2012 10:00:00 AM}, {id: 2, date: Mar 8 2012 08:00:00 AM}];
How can I sort this array by the date element in order from the date closest to the current date and time down? Keep in mind that the array may have many objects, but for the sake of simplicity I used 2.
如何按日期元素从最接近当前日期和时间的日期开始对这个数组进行排序?请记住,数组可能有很多对象,但为了简单起见,我使用了 2。
Would I use the sort function and a custom comparator?
我会使用排序功能和自定义比较器吗?
UPDATE:
更新:
In my specific case, I wanted the dates arranged from the most recent to the oldest. It ended up that I had to reverse the simple function's logic as so:
在我的特定情况下,我希望日期从最近到最旧排列。最终我不得不将简单函数的逻辑颠倒如下:
array.sort(function(a, b) {
a = new Date(a.dateModified);
b = new Date(b.dateModified);
return a>b ? -1 : a<b ? 1 : 0;
});
This sorts the dates from the most recent.
这对最近的日期进行排序。
回答by Phrogz
Simplest Answer
最简单的答案
array.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.date) - new Date(a.date);
});
More Generic Answer
更通用的答案
array.sort(function(o1,o2){
if (sort_o1_before_o2) return -1;
else if(sort_o1_after_o2) return 1;
else return 0;
});
Or more tersely:
或者更简洁:
array.sort(function(o1,o2){
return sort_o1_before_o2 ? -1 : sort_o1_after_o2 ? 1 : 0;
});
Generic, Powerful Answer
通用、强大的答案
Define a custom non-enumerable sortBy
function using a Schwartzian transformon all arrays :
在所有数组上sortBy
使用Schwartzian 变换定义一个自定义的不可枚举函数:
(function(){
if (typeof Object.defineProperty === 'function'){
try{Object.defineProperty(Array.prototype,'sortBy',{value:sb}); }catch(e){}
}
if (!Array.prototype.sortBy) Array.prototype.sortBy = sb;
function sb(f){
for (var i=this.length;i;){
var o = this[--i];
this[i] = [].concat(f.call(o,o,i),o);
}
this.sort(function(a,b){
for (var i=0,len=a.length;i<len;++i){
if (a[i]!=b[i]) return a[i]<b[i]?-1:1;
}
return 0;
});
for (var i=this.length;i;){
this[--i]=this[i][this[i].length-1];
}
return this;
}
})();
Use it like so:
像这样使用它:
array.sortBy(function(o){ return o.date });
If your date is not directly comparable, make a comparable date out of it, e.g.
如果您的日期不能直接比较,请从中制作一个可比较的日期,例如
array.sortBy(function(o){ return new Date( o.date ) });
You can also use this to sort by multiple criteria if you return an array of values:
如果您返回一个值数组,您还可以使用它按多个条件排序:
// Sort by date, then score (reversed), then name
array.sortBy(function(o){ return [ o.date, -o.score, o.name ] };
See http://phrogz.net/JS/Array.prototype.sortBy.jsfor more details.
有关更多详细信息,请参阅http://phrogz.net/JS/Array.prototype.sortBy.js。
回答by Gal
@Phrogz answers are both great, but here is a great, more concise answer:
@Phrogz 的答案都很棒,但这里有一个很棒的、更简洁的答案:
array.sort(function(a,b){return a.getTime() - b.getTime()});
Using the arrow function way
使用箭头函数方式
array.sort((a,b)=>a.getTime()-b.getTime());
found here: Sort date in Javascript
在这里找到:在 Javascript 中对日期进行排序
回答by qw3n
After correcting the JSON this should work for you now:
更正 JSON 后,这现在应该对您有用:
var array = [{id: 1, date:'Mar 12 2012 10:00:00 AM'}, {id: 2, date:'Mar 8 2012 08:00:00 AM'}];
array.sort(function(a, b) {
var c = new Date(a.date);
var d = new Date(b.date);
return c-d;
});
回答by gabitzish
Your data needs some corrections:
您的数据需要一些更正:
var array = [{id: 1, date: "Mar 12 2012 10:00:00 AM"},{id: 2, date: "Mar 28 2012 08:00:00 AM"}];
After correcting the data, you can use this piece of code:
更正数据后,可以使用这段代码:
function sortFunction(a,b){
var dateA = new Date(a.date).getTime();
var dateB = new Date(b.date).getTime();
return dateA > dateB ? 1 : -1;
};
var array = [{id: 1, date: "Mar 12 2012 10:00:00 AM"},{id: 2, date: "Mar 28 2012 08:00:00 AM"}];
array.sort(sortFunction);?
回答by jherax
I recommend GitHub: Array sortBy- a best implementation of sortBy
method which uses the Schwartzian transform
我推荐GitHub:Array sortBy-sortBy
使用Schwartzian 变换的方法的最佳实现
But for now we are going to try this approach Gist: sortBy-old.js.
Let's create a method to sort arrays being able to arrange objects by some property.
但是现在我们将尝试这种方法要点: sortBy-old.js。
让我们创建一个方法来对数组进行排序,以便能够按某些属性排列对象。
Creating the sorting function
创建排序函数
var sortBy = (function () {
var toString = Object.prototype.toString,
// default parser function
parse = function (x) { return x; },
// gets the item to be sorted
getItem = function (x) {
var isObject = x != null && typeof x === "object";
var isProp = isObject && this.prop in x;
return this.parser(isProp ? x[this.prop] : x);
};
/**
* Sorts an array of elements.
*
* @param {Array} array: the collection to sort
* @param {Object} cfg: the configuration options
* @property {String} cfg.prop: property name (if it is an Array of objects)
* @property {Boolean} cfg.desc: determines whether the sort is descending
* @property {Function} cfg.parser: function to parse the items to expected type
* @return {Array}
*/
return function sortby (array, cfg) {
if (!(array instanceof Array && array.length)) return [];
if (toString.call(cfg) !== "[object Object]") cfg = {};
if (typeof cfg.parser !== "function") cfg.parser = parse;
cfg.desc = !!cfg.desc ? -1 : 1;
return array.sort(function (a, b) {
a = getItem.call(cfg, a);
b = getItem.call(cfg, b);
return cfg.desc * (a < b ? -1 : +(a > b));
});
};
}());
Setting unsorted data
设置未排序的数据
var data = [
{date: "2011-11-14T17:25:45Z", quantity: 2, total: 200, tip: 0, type: "cash"},
{date: "2011-11-14T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
{date: "2011-11-14T16:30:43Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T17:22:59Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T16:53:41Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T16:48:46Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "visa"},
{date: "2011-11-01T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},
{date: "2011-11-14T16:58:03Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T16:20:19Z", quantity: 2, total: 190, tip: 100, type: "tab"},
{date: "2011-11-14T17:07:21Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0, type: "cash"}
];
Using it
使用它
Finally, we arrange the array, by "date"
property as string
最后,我们按"date"
属性排列数组string
//sort the object by a property (ascending)
//sorting takes into account uppercase and lowercase
sortBy(data, { prop: "date" });
If you want to ignore letter case, set the "parser"
callback:
如果要忽略字母大小写,请设置"parser"
回调:
//sort the object by a property (descending)
//sorting ignores uppercase and lowercase
sortBy(data, {
prop: "date",
desc: true,
parser: function (item) {
//ignore case sensitive
return item.toUpperCase();
}
});
If you want to treat the "date" field as Date
type:
如果要将“日期”字段视为Date
类型:
//sort the object by a property (ascending)
//sorting parses each item to Date type
sortBy(data, {
prop: "date",
parser: function (item) {
return new Date(item);
}
});
Here you can play with the above example:
jsbin.com/lesebi
在这里你可以玩上面的例子:
jsbin.com/lesebi
回答by Edison D'souza
This should do when your date is in this format (dd/mm/yyyy).
当您的日期采用这种格式 (dd/mm/yyyy) 时,应该这样做。
sortByDate(arr) {
arr.sort(function(a,b){
return Number(new Date(a.readableDate)) - Number(new Date(b.readableDate));
});
return arr;
}
Then call sortByDate(myArr);
然后打电话 sortByDate(myArr);
回答by Robert
You could use sortBy in underscore js.
您可以在下划线 js 中使用 sortBy。
http://underscorejs.org/#sortBy
http://underscorejs.org/#sortBy
Sample:
样本:
var log = [{date: '2016-01-16T05:23:38+00:00', other: 'sample'},
{date: '2016-01-13T05:23:38+00:00',other: 'sample'},
{date: '2016-01-15T11:23:38+00:00', other: 'sample'}];
console.log(_.sortBy(log, 'date'));
回答by James111
I'm going to add this here, as some uses may not be able to work out how to invert this sorting method.
我将在这里添加这个,因为有些用户可能无法弄清楚如何反转这种排序方法。
To sort by 'coming up', we can simply swap a & b, like so:
要按“出现”排序,我们可以简单地交换 a & b,如下所示:
your_array.sort ( (a, b) => {
return new Date(a.DateTime) - new Date(b.DateTime);
});
Notice that a
is now on the left hand side, and b
is on the right, :D!
请注意,a
现在在左侧,b
在右侧,:D!
回答by Amay Kulkarni
i was able to achieve sorting using below lines:
我能够使用以下几行实现排序:
array.sort(function(a, b)
{
if (a.DueDate > b.DueDate) return 1;
if (a.DueDate < b.DueDate) return -1;
})
回答by Aravinda Meewalaarachchi
I personally use following approach to sort dates.
我个人使用以下方法对日期进行排序。
let array = ["July 11, 1960", "February 1, 1974", "July 11, 1615", "October 18, 1851", "November 12, 1995"];
array.sort(function(date1, date2) {
date1 = new Date(date1);
date2 = new Date(date2);
if (date1 > date2) return 1;
if (date1 < date2) return -1;
})