javascript - JS object sorting date sorting -


i have js object defined follows -

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

at point in app getting list of (items) chrome.storage , able sort based on date

here 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) {                 = new date(a[1].date);                 b = new date(b[1].date);                 return > b ? -1 : < b ? 1 : 0;             });              console.log(sortable); 

it doesn't seem work. first , second console.log(sortable); same. have tried changing return > b ? -1 : < b ? 1 : 0; return < b ? -1 : > b ? 1 : 0; see if getting change sortable nothing happens... thank you~

both console.log show same array because when use console.log(sortable), sortable passed reference, , console output happens after finishing script - when sortable has been sorted.

making code simple:

var arr = [3,2,1]; console.log(arr); // produces `[1,2,3]` because printed                   // console after `arr.sort();` arr.sort(); console.log(arr); // produces `[1,2,3]`, expected 

demo: http://jsfiddle.net/rfwph/


workaround

if want able console.log array see before being modifyed, can use .slice(0) copy array, i.e. obtain another array contains same elements 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: better use .slice(0) instead of .slice(), supported on ff ecma262 spec says end argument optional.


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -