Javascript 按具有日期值的单个键对对象数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8837454/
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 array of objects by single key with date value
提问by Rocket Hazmat
I have an array of objects with several key value pairs, and I need to sort them based on 'updated_at':
我有一个包含多个键值对的对象数组,我需要根据“updated_at”对它们进行排序:
[
{
"updated_at" : "2012-01-01T06:25:24Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-09T11:25:13Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-05T04:13:24Z",
"foo" : "bar"
}
]
What's the most efficient way to do so?
这样做的最有效方法是什么?
回答by Rocket Hazmat
You can use Array.sort
.
您可以使用Array.sort
.
Here's an example:
下面是一个例子:
var arr = [{
"updated_at": "2012-01-01T06:25:24Z",
"foo": "bar"
},
{
"updated_at": "2012-01-09T11:25:13Z",
"foo": "bar"
},
{
"updated_at": "2012-01-05T04:13:24Z",
"foo": "bar"
}
]
arr.sort(function(a, b) {
var keyA = new Date(a.updated_at),
keyB = new Date(b.updated_at);
// Compare the 2 dates
if (keyA < keyB) return -1;
if (keyA > keyB) return 1;
return 0;
});
console.log(arr);
回答by David Brainer
I already answered a really similar question here: Simple function to sort an array of objects
我已经在这里回答了一个非常相似的问题:Simple function to sort an array of objects
For that question I created this little function that might do what you want:
对于那个问题,我创建了这个小函数,它可能会做你想做的事:
function sortByKey(array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
回答by Patrick W. McMahon
The Array.sort()method sorts the elements of an array in place and returns the array. Be careful with Array.sort()as it's not Immutable. For immutable sort use immutable-sort.
所述的Array.sort()方法进行排序的阵列的代替元素并返回数组。小心Array.sort()因为它不是Immutable。对于不可变排序,请使用immutable-sort。
This method is to sort the array using your current updated_at
in ISO format. We use new Data(iso_string).getTime()
to convert ISO time to Unix timestamp. A Unix timestamp is a number that we can do simple math on. We subtract the first and second timestamp the result is; if the first timestamp is bigger than the second the return number will be positive. If the second number is bigger than the first the return value will be negative. If the two are the same the return will be zero. This alines perfectly with the required return values for the inline function.
此方法是使用当前updated_at
的 ISO 格式对数组进行排序。我们new Data(iso_string).getTime()
用来将 ISO 时间转换为 Unix 时间戳。Unix 时间戳是一个我们可以做简单数学运算的数字。我们减去第一个和第二个时间戳,结果是;如果第一个时间戳大于第二个,则返回数字将为正。如果第二个数字大于第一个,则返回值将为负数。如果两者相同,则返回为零。这与内联函数所需的返回值完全一致。
For ES6:
对于ES6:
arr.sort((a,b) => new Date(a.updated_at).getTime() - new Date(b.updated_at).getTime());
For ES5:
对于ES5:
arr.sort(function(a,b){
return new Date(a.updated_at).getTime() - new Date(b.updated_at).getTime();
});
If you change your updated_at
to be unix timestamps you can do this:
如果您将您的updated_at
时间戳更改为 unix 时间戳,您可以执行以下操作:
For ES6:
对于ES6:
arr.sort((a,b) => a.updated_at - b.updated_at);
For ES5:
对于ES5:
arr.sort(function(a,b){
return a.updated_at - b.updated_at;
});
At the time of this post, modern browsers do not support ES6. To use ES6 in modern browsers use babelto transpile the code to ES5. Expect browser support for ES6 in the near future.
在撰写本文时,现代浏览器不支持 ES6。要在现代浏览器中使用 ES6,请使用babel将代码转换为 ES5。期待浏览器在不久的将来支持 ES6。
Array.sort()should receave a return value of one of 3 possible outcomes:
Array.sort()应该接收 3 种可能结果之一的返回值:
- A positive number (first item > second item)
- A negative number (first item < second item)
- 0 if the two items are equal
- 一个正数(第一项 > 第二项)
- 负数(第一项 < 第二项)
- 0 如果两项相等
Note that the return value on the inline function can be any positive or negative number. Array.Sort() does not care what the return number is. It only cares if the return value is positive, negative or zero.
请注意,内联函数的返回值可以是任何正数或负数。Array.Sort() 不关心返回数字是什么。它只关心返回值是正数、负数还是零。
For Immutable sort: (example in ES6)
对于不可变排序:(以 ES6 为例)
const sort = require('immutable-sort');
const array = [1, 5, 2, 4, 3];
const sortedArray = sort(array);
You can also write it this way:
你也可以这样写:
import sort from 'immutable-sort';
const array = [1, 5, 2, 4, 3];
const sortedArray = sort(array);
The import-from you see is a new way to include javascript in ES6 and makes your code look very clean. My personal favorite.
您看到的 import-from 是一种在 ES6 中包含 javascript 的新方法,并使您的代码看起来非常干净。我个人的最爱。
Immutable sort doesn't mutate the source array rather it returns a new array. Using const
is recommended on immutable data.
不可变排序不会改变源数组,而是返回一个新数组。使用const
建议不可变的数据。
回答by Brad Parks
Here's a slightly modified version of @David Brainer-Bankers answerthat sorts alphabetically by string, or numerically by number, and ensures that words beginning with Capital letters don't sort above words starting with a lower case letter (e.g "apple,Early" would be displayed in that order).
这是@David Brainer-Bankers 答案的略微修改版本,它按字符串或数字按字母顺序排序,并确保以大写字母开头的单词不会排在以小写字母开头的单词之上(例如“apple,Early”将按该顺序显示)。
function sortByKey(array, key) {
return array.sort(function(a, b) {
var x = a[key];
var y = b[key];
if (typeof x == "string")
{
x = (""+x).toLowerCase();
}
if (typeof y == "string")
{
y = (""+y).toLowerCase();
}
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
回答by Mohammed Safeer
Use underscore js or lodash,
使用下划线 js 或 lodash,
var arrObj = [
{
"updated_at" : "2012-01-01T06:25:24Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-09T11:25:13Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-05T04:13:24Z",
"foo" : "bar"
}
];
arrObj = _.sortBy(arrObj,"updated_at");
_.sortBy()
returns a new array
_.sortBy()
返回一个新数组
refer http://underscorejs.org/#sortByand lodash docs https://lodash.com/docs#sortBy
参考http://underscorejs.org/#sortBy和 lodash 文档https://lodash.com/docs#sortBy
回答by knowbody
With ES2015 support it can be done by:
有了 ES2015 支持,它可以通过以下方式完成:
foo.sort((a, b) => a.updated_at < b.updated_at ? -1 : 1)
回答by Anandan K
Data Imported
数据导入
[
{
"gameStatus": "1",
"userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
"created_at": "2018-12-20 11:32:04"
},
{
"gameStatus": "0",
"userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
"created_at": "2018-12-19 18:08:24"
},
{
"gameStatus": "2",
"userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
"created_at": "2018-12-19 18:35:40"
},
{
"gameStatus": "0",
"userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
"created_at": "2018-12-19 10:42:53"
},
{
"gameStatus": "2",
"userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
"created_at": "2018-12-20 10:54:09"
},
{
"gameStatus": "0",
"userId": "1a2fefb0-5ae2-47eb-82ff-d1b2cc27875a",
"created_at": "2018-12-19 18:46:22"
},
{
"gameStatus": "1",
"userId": "7118ed61-d8d9-4098-a81b-484158806d21",
"created_at": "2018-12-20 10:50:48"
}
]
FOR Ascending order
FOR 升序
arr.sort(function(a, b){
var keyA = new Date(a.updated_at),
keyB = new Date(b.updated_at);
// Compare the 2 dates
if(keyA < keyB) return -1;
if(keyA > keyB) return 1;
return 0;
});
Example for Asc Order
升序示例
[
{
"gameStatus": "0",
"userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
"created_at": "2018-12-19 10:42:53"
},
{
"gameStatus": "0",
"userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
"created_at": "2018-12-19 18:08:24"
},
{
"gameStatus": "2",
"userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
"created_at": "2018-12-19 18:35:40"
},
{
"gameStatus": "0",
"userId": "1a2fefb0-5ae2-47eb-82ff-d1b2cc27875a",
"created_at": "2018-12-19 18:46:22"
},
{
"gameStatus": "1",
"userId": "7118ed61-d8d9-4098-a81b-484158806d21",
"created_at": "2018-12-20 10:50:48"
},
{
"gameStatus": "2",
"userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
"created_at": "2018-12-20 10:54:09"
},
{
"gameStatus": "1",
"userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
"created_at": "2018-12-20 11:32:04"
}
]
FOR Descending order
FOR 降序
arr.sort(function(a, b){
var keyA = new Date(a.updated_at),
keyB = new Date(b.updated_at);
// Compare the 2 dates
if(keyA > keyB) return -1;
if(keyA < keyB) return 1;
return 0;
});
Example for Desc Order
降序示例
[
{
"gameStatus": "1",
"userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
"created_at": "2018-12-20 11:32:04"
},
{
"gameStatus": "2",
"userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
"created_at": "2018-12-20 10:54:09"
},
{
"gameStatus": "1",
"userId": "7118ed61-d8d9-4098-a81b-484158806d21",
"created_at": "2018-12-20 10:50:48"
},
{
"gameStatus": "0",
"userId": "1a2fefb0-5ae2-47eb-82ff-d1b2cc27875a",
"created_at": "2018-12-19 18:46:22"
},
{
"gameStatus": "2",
"userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
"created_at": "2018-12-19 18:35:40"
},
{
"gameStatus": "0",
"userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
"created_at": "2018-12-19 18:08:24"
},
{
"gameStatus": "0",
"userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
"created_at": "2018-12-19 10:42:53"
}
]
回答by Ishpreet
As Thisanswer's states, you can use Array.sort
.
由于此答案的状态,你可以使用Array.sort
。
arr.sort(function(a,b){return new Date(a.updated_at) - new Date(b.updated_at)})
arr.sort(function(a,b){return new Date(a.updated_at) - new Date(b.updated_at)})
arr = [
{
"updated_at" : "2012-01-01T06:25:24Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-09T11:25:13Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-05T04:13:24Z",
"foo" : "bar"
}
];
arr.sort(function(a,b){return new Date(a.updated_at) - new Date(b.updated_at)});
console.log(arr);
回答by Danny Mor
Just another, more mathematical, way of doing the same thing but shorter:
只是另一种更数学化的做同样事情但更短的方法:
arr.sort(function(a, b){
var diff = new Date(a.updated_at) - new Date(b.updated_at);
return diff/(Math.abs(diff)||1);
});
or in the slick lambda arrow style:
或在光滑的 lambda 箭头样式中:
arr.sort((a, b) => {
var diff = new Date(a.updated_at) - new Date(b.updated_at);
return diff/(Math.abs(diff)||1);
});
This method can be done with any numeric input
这种方法可以用任何数字输入来完成
回答by Fyodor
As for today, answers of @knowbody (https://stackoverflow.com/a/42418963/6778546) and @Rocket Hazmat (https://stackoverflow.com/a/8837511/6778546) can be combined to provide for ES2015 support and correct date handling:
至于今天,@knowbody ( https://stackoverflow.com/a/42418963/6778546) 和@Rocket Hazmat ( https://stackoverflow.com/a/8837511/6778546) 的答案可以结合起来提供 ES2015 支持和正确的日期处理:
arr.sort((a, b) => {
const dateA = new Date(a.updated_at);
const dateB = new Date(b.updated_at);
return dateA - dateB;
});