lin lin - 4 years ago 109
Javascript Question

AngularJS / JavaScript: Order array of objects digit by digit

I have some special request for you all. I need a custom order / sorting for the following array of objects. The array I need to order could look like the following example:

//array
$scope.myArray = [
{
orderId: "100"
}, {
orderId: "02"
}, {
orderId: "020"
}, {
orderId: "90"
}, {
orderId: "9"
},{
orderId: "52222"
}, {
orderId: "5223"
}, {
orderId: "522"
}, {
orderId: "800"
}, {
orderId: "080001"
}, {
orderId: "0009"
}
];


The main problem is, that I have to order this objects in
$scope.myArray
by the attributes
orderId
digit by digit. I already tried it with
$scope.myTest = $filter('orderBy')($scope.myTest, 'orderId', false);
but as aspected, this does not order my attribute digit by digit.

This is how the result should look like:




//abstract result order
0009, 02, 020, 080001, 100, 522, 52222, 5223, 800, 9, 90



//array ordered
$scope.myArray = [
{
orderId: "0009"
}, {
orderId: "02"
}, {
orderId: "020"
}, {
orderId: "080001"
}, {
orderId: "100"
},{
orderId: "522"
}, {
orderId: "52222"
}, {
orderId: "5223"
}, {
orderId: "800"
}, {
orderId: "9"
}, {
orderId: "90"
}
];

Answer Source

You could take the build in sort of Javascript and sort by the property as string.

$scope = { myArray: [{ orderId: "100" }, { orderId: "02" }, { orderId: "020" }, { orderId: "90" }, { orderId: "9" }, { orderId: "52222" }, { orderId: "5223" }, { orderId: "522" }, { orderId: "800" }, { orderId: "080001" }, { orderId: "0009" }] };

$scope.myArray.sort(function (a, b) {
    return a.orderId.localeCompare(b.orderId);
});

console.log($scope.myArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download