Sort by id in Angularjs (Javascript)

Asked

Viewed 159 times

1

I have an Angularjs object:

$scope.listaDoCarrinho = [0: {
        id: "55",
        setor: "alimento",
        foto: "Produtos/Produto (55).jpg",
        descr: "Espaguete Renata",
        de: 15,
        …
    }
    1: {
        id: "1000",
        setor: "biscoitos",
        foto: "Produtos/Produto (1000).jpg",
        descr: "Biscoito Pit-Stop",
        de: 3,
        …
    }
    2: {
        id: "3",
        setor: "higiene",
        foto: "Produtos/Produto (3).jpg",
        descr: "Bronzeador 200ml",
        de: 15,
        …
    }
];

I need to change this sequence by id (3 -> 55 -> 1000). There is a way to do it without ng-repeat?

Obs: the "-" (dash) in the code is only to inform that the array has more insignificant properties.

1 answer

1


You can use the $filter orderBy:

$scope.listaDoCarrinho = $filter('orderBy')($scope.listaDoCarrinho, 'id');

But look, your attribute id is a String, therefore it will be ordered alphabetically.


orderBy

Returns an array containing the items from the specified Collection, ordered by a Comparator Function based on the values computed using the Expression predicate.

In free translation:

Returns an array containing the items of a specified collection, ordered by a comparison function based on the values computed using the predicative expression.

  • In doing so, the console says "Referenceerror: filter is not defined".

  • 1

    @Guilhermesilvadeoliveira has to import $filter, he did this?

  • No, I’ve never actually used $filter... I’ll look up how to import it.

  • I did it. To sort it in ascending order, just take the quotes from the id, right?

  • 1

    @Guilhermesilvadeoliveira exact

Browser other questions tagged

You are not signed in. Login or sign up in order to post.