use*_*192 39 javascript arrays sorting lodash
我有一个JavaScript对象数组.我的数组定义如下:
var myObjects = [
{ id: '1', username: 'bill.jones', active: true, createdon: '03/29/2014' },
{ id: '2', username: 'woohoo', active: true, createdon: '03/28/2014' },
{ id: '3', username: 'someuser', active: true, createdon: '03/30/2014' }
];
Run Code Online (Sandbox Code Playgroud)
该数组实际上是动态填充的.不过,我需要按创建的值按升序对结果进行排序.为此,我正在尝试使用lodash.createdon值表示日期.目前,我正在尝试以下方法:
// ORDER BY createdOn
myObjects.sort(function (a, b) {
var date1 = new Date(a['createdon']);
var date2 = new Date(b['createdon']);
return date1 < date2;
});
_.forEach(myObjects, function(result) {
console.log(result);
});
Run Code Online (Sandbox Code Playgroud)
不幸的是,在运行此函数后,myObjects仍未排序.我究竟做错了什么?
谢谢!
lco*_*rre 73
我刚刚通过了lodash doc,也许你可以试试sortBy
试一试:http://jsfiddle.net/3Wza8/
var myObjects = [
{ id: '1', username: 'bill.jones', active: true, createdon: new Date('03/29/2014') },
{ id: '2', username: 'woohoo', active: true, createdon: new Date('03/28/2014') },
{ id: '3', username: 'someuser', active: true, createdon: new Date('03/30/2014') }
];
myObjects = _.sortBy(myObjects, 'createdon');
_.forEach(myObjects, function (result) {
console.log(result);
});
Run Code Online (Sandbox Code Playgroud)
编辑:正如Cookie Monster指出的那样,重要的是你的createdon字段是Date,而不是字符串.
| 归档时间: |
|
| 查看次数: |
43293 次 |
| 最近记录: |