Skip to content Skip to sidebar Skip to footer

Js Object Sorting Date Sorting

I have JS object defined as follows - var item = {}; item[guid()] = { symbol: $('#qteSymb').text(), note: $('#newnote').val(), date: $.datepicker.formatDate('mm/dd/yy',

Solution 1:

Both console.log show the same array because when you use console.log(sortable), sortable is passed by reference, and console output happens AFTER finishing your script - when sortable has been already sorted.

Making your code simple:

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/


Workaround

If you want to be able to do console.log with an array to see it before being modifyed, you can use .slice(0) to copy the array, i.e. to obtain another array which 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: better use .slice(0) instead of .slice(), which is supported on FF but ecma262 spec says only end argument is optional.

Solution 2:

@Oriol:

I just did an identical fiddle http://jsfiddle.net/JaU4g/ , but for me it DID work!

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"

Post a Comment for "Js Object Sorting Date Sorting"