extempl extempl - 1 month ago 7
Javascript Question

Array.sort random function does not works in iPhone's Safari

Here is my code:

var array = 'BCDFGA'.split('');

var sorted = array.sort(function () {
return Math.floor(Math.random() * 2);
});

alert(JSON.stringify(sorted)); // B, C, D, F, G, A


See it on jsbin

What I'm doing wrong?

I saw this post, but I totally do not understand why it is not working with random.

Answer
 $scope.filtercolumn1.sort(function(a,b){
                var nameA = a.label.toUpperCase(); // ignore upper and lowercase
                var nameB = b.label.toUpperCase(); // ignore upper and lowercase
                if (nameA < nameB) {
                return -1;
                }
                if (nameA > nameB) {
                return 1;
                }

                // names must be equal
                return 0;
            })
Comments