Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of JavaScript objects by property value [duplicate]

I have an array of JavaScript objects. My array is defined like this:

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' } ]; 

This array is actually dynamically populated. Still, I need to sort the results by the createdon value in ascending order. To do that, I'm trying to use lodash. The createdon value represents a date. Currently, I'm trying the following:

//  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); }); 

Unfortunately, myObjects is still not sorted after I run this function. What am I doing wrong?

Thank you!

like image 614
user70192 Avatar asked Jul 03 '14 18:07

user70192


2 Answers

I just went through lodash doc, and perhaps you could try sortBy

Try it: 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); }); 

EDIT: as Cookie Monster pointed out, it's important that your createdon field is a Date, and not a string.

like image 111
lcoderre Avatar answered Sep 23 '22 00:09

lcoderre


The problem is that sort expects a function which returns -1, 0 or 1. Your function only returns 0 and 1.

This slight change should fix it:

myObjects.sort(function (a, b) {   var date1 = new Date(a['createdon']);   var date2 = new Date(b['createdon']);   return date1 - date2; }); 
like image 41
Joe Frambach Avatar answered Sep 26 '22 00:09

Joe Frambach