Sort JS objects sort date

I have a JS object defined as follows:

var item = {}; item[guid()] = { symbol: $('#qteSymb').text(), note: $('#newnote').val(), date: $.datepicker.formatDate('mm/dd/yy', dt) + " " + dt.getHours() + ":" + minutes, pagename: getPageName() }; 

At some point in my application, I get a list of those ( Items ) back from chrome.storage, and I would like to be able to sort it based on date

That's what I'm doing

 var sortable = []; $.each(Items, function (key, value) { if (value.symbol == $('#qteSymb').text() || all) { sortable.push([key, value]); } }); console.log(sortable); sortable.sort(function (a, b) { a = new Date(a[1].date); b = new Date(b[1].date); return a > b ? -1 : a < b ? 1 : 0; }); console.log(sortable); 

It does not seem to work. The first and second console.log(sortable); match up. I tried changing return a > b ? -1 : a < b ? 1 : 0; return a > b ? -1 : a < b ? 1 : 0; on return a < b ? -1 : a > b ? 1 : 0; return a < b ? -1 : a > b ? 1 : 0; just to see if there are any changes to sortable , but nothing happens ... Thanks ~

+1
javascript jquery
source share
2 answers

Both console.log show the same array, because when you use console.log(sortable) , sortable is passed by reference, and the console exits after your script completes - when sortable already sorted.

Simple code:

 var arr = [3,2,1]; console.log(arr); // Produces `[1,2,3]` because its printed // to the console after `arr.sort();` arr.sort(); console.log(arr); // Produces `[1,2,3]`, as expected 

Demo : http://jsfiddle.net/Rfwph/


Bypass

If you want to make console.log with an array to see it before changing, you can use .slice(0) to copy the array, i.e. to get an array of another that contains the same elements as your array.

 var arr = [3,2,1]; console.log(arr.slice(0)); // [3,2,1] arr.sort(); console.log(arr); // [1,2,3] 

Demo : http://jsfiddle.net/Rfwph/2/

Edit: It is better to use .slice(0) instead of .slice() , which is supported in FF, but the ecma262 specification says that the end argument is optional.

+1
source share

@Oriol:

I just made the same fiddle http://jsfiddle.net/JaU4g/ , but it worked for me!

 var ar=[3,1,8,4,7,2,4,1] console.log(ar.join(',')); ar.sort(); console.log(ar.join(',')); 

giving:

 [18:55:31.616] "3,1,8,4,7,2,4,1" [18:55:31.616] "1,1,2,3,4,4,7,8" 
0
source share

All Articles