Chuck Villavicencio
Chuck Villavicencio

Reputation: 393

Order data from array asc or desc using .sort

I'm getting info from a json file, and i'm trying to order asc and desc. This is my code so far:

    $scope.fromLessToMore = function(){
        var filteringBy = [];

        $http.get('/app/json/file.json')
        .then(function(data){
            $scope.listOfProducts = data.data.products;

                for(var i = 0; i< $scope.listOfProducts.length; i++){
                    if($scope.listOfProducts[i].id === $scope.inside){
                        filteringBy.push($scope.listOfProducts[i]);
                    }
                }

                //$scope.normalData = filteringBy;
                $scope.dataOnFilter = filteringBy.sort((a, b) => (a.price > b.price) ? 1 : ((b.price > a.price) ? -1 : 0));
        });

    }

As you can see, i'm using filteringBy.sort((a, b) => (a.price > b.price) ? 1 : ((b.price > a.price) ? -1 : 0)); and it works, but the numbers are ordered like this:

$1, $100, $1000, $2, $200, $3, $30

What can i do to order correctly ($1, $2, $3, $30...)? I've tried with ES6: filteringBy.sort((a,b) => a.price - b.price);, and filteringBy.sort((a,b) => a - b.price); but is not working, and don't have any errors on the console.

Someone can help me, please?

I'm using AngularJs and Javascript.

Upvotes: 0

Views: 59

Answers (3)

Mukund
Mukund

Reputation: 393

As your contents are in string/currency format you will need to convert currency/string into number and then sort them. we can do something like below,

    filteringBy = [{price:'$10'},{price:'$110'},{price:'$20'},{price:'$30'}, {price:'$510'}]; 
filteringBy.sort((a, b) => (Number(a.price.replace('$','')) > Number(b.price.replace('$', ''))) ? 1 : ((Number(b.price.replace('$','')) > Number(a.price.replace('$',''))) ? -1 : 0));

Upvotes: 0

Just code
Just code

Reputation: 13801

I do not encourage sorting like this, but you can replace non-digt values using \D and then apply sorting.

filteringBy = ['$1', '$100', '$1000', '$2', '$200', '$3', '$30'];
var filtered = filteringBy.sort((a, b) => {

var aPrice = parseInt(a.replace(/\D/g,''));
var bPrice = parseInt(b.replace(/\D/g,''));
return (aPrice > bPrice) ? 1 : ((bPrice > aPrice) ? -1 : 0)
});

console.log(filtered);

You should try using integer from database it self.

Upvotes: 2

dotconnor
dotconnor

Reputation: 1786

Your current values are string, and strings are compared on a per character basis, so the current sorts are correct. To achieve the sort order you need consider parsing them as Numbers fist:

// The slice removes the dollar sign
filteringBy = filteringBy.map((a) => Number.parseFloat(a.slice(1)));

Upvotes: 0

Related Questions